Datasets:
Update terramesh.py
Browse files- terramesh.py +85 -33
terramesh.py
CHANGED
|
@@ -21,11 +21,11 @@ import io
|
|
| 21 |
import re
|
| 22 |
import zarr
|
| 23 |
import torch
|
|
|
|
| 24 |
import fsspec
|
| 25 |
import braceexpand
|
| 26 |
-
import numpy as np
|
| 27 |
import albumentations
|
| 28 |
-
import
|
| 29 |
import webdataset as wds
|
| 30 |
from collections.abc import Callable, Iterable
|
| 31 |
from torch.utils.data._utils.collate import default_collate
|
|
@@ -75,29 +75,62 @@ statistics = {
|
|
| 75 |
|
| 76 |
def build_terramesh_dataset(
|
| 77 |
path: str = "https://huggingface.co/datasets/ibm-esa-geospatial/TerraMesh/resolve/main/",
|
| 78 |
-
modalities: list | str = None,
|
| 79 |
split: str = "val",
|
| 80 |
urls: str | None = None,
|
|
|
|
| 81 |
batch_size: int = 8,
|
| 82 |
return_metadata: bool = False,
|
| 83 |
shuffle: bool = True,
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
| 85 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
if len(modalities) == 1:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
# Build standard WebDataset for single modality
|
| 88 |
dataset = build_wds_dataset(
|
| 89 |
path=path,
|
| 90 |
-
modality=modalities
|
| 91 |
split=split,
|
| 92 |
urls=urls,
|
| 93 |
batch_size=batch_size,
|
|
|
|
| 94 |
return_metadata=return_metadata,
|
| 95 |
shuffle=shuffle,
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
| 97 |
)
|
| 98 |
return dataset
|
| 99 |
|
| 100 |
else:
|
|
|
|
|
|
|
|
|
|
| 101 |
# Build custom multi-modal dataset
|
| 102 |
dataset = build_multimodal_dataset(
|
| 103 |
path=path,
|
|
@@ -105,9 +138,12 @@ def build_terramesh_dataset(
|
|
| 105 |
split=split,
|
| 106 |
urls=urls,
|
| 107 |
batch_size=batch_size,
|
|
|
|
| 108 |
return_metadata=return_metadata,
|
| 109 |
shuffle=shuffle,
|
| 110 |
-
|
|
|
|
|
|
|
| 111 |
)
|
| 112 |
return dataset
|
| 113 |
|
|
@@ -118,6 +154,10 @@ def zarr_decoder(key, value):
|
|
| 118 |
return zarr.open_consolidated(mapper, mode="r")["bands"][...]
|
| 119 |
|
| 120 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
def zarr_metadata_decoder(sample):
|
| 122 |
for key, value in list(sample.items()):
|
| 123 |
if key == "zarr.zip" or key.endswith(".zarr.zip"):
|
|
@@ -134,7 +174,12 @@ def zarr_metadata_decoder(sample):
|
|
| 134 |
if data["time"][...] > 1e6: # DEM has no valid timestamp (value = 0)
|
| 135 |
time_key = "time" if key == "zarr.zip" else "time_" + key
|
| 136 |
sample[time_key] = data["time"][...] # Integer values of type "datetime64[ns]"
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
return sample
|
| 140 |
|
|
@@ -167,6 +212,10 @@ def build_wds_dataset(
|
|
| 167 |
transform: Callable = None,
|
| 168 |
shuffle: bool = True,
|
| 169 |
return_metadata: bool = False,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
*args, **kwargs
|
| 171 |
):
|
| 172 |
if urls is None:
|
|
@@ -183,10 +232,23 @@ def build_wds_dataset(
|
|
| 183 |
[os.path.join(path, split, modality, f) for f in files]
|
| 184 |
)
|
| 185 |
|
| 186 |
-
|
|
|
|
|
|
|
| 187 |
|
| 188 |
# Build dataset
|
| 189 |
-
dataset = wds.WebDataset(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
# Decode from bytes to numpy arrays, etc.
|
| 192 |
dataset = dataset.map(zarr_metadata_decoder) if return_metadata else dataset.decode(zarr_decoder)
|
|
@@ -216,7 +278,10 @@ def build_multimodal_dataset(
|
|
| 216 |
transform: Callable = None,
|
| 217 |
shuffle: bool = True,
|
| 218 |
return_metadata: bool = False,
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
| 220 |
):
|
| 221 |
if modalities is None:
|
| 222 |
modalities = ["S2L2A", "S2L1C", "S2RGB", "S1GRD", "S1RTC", "DEM", "NDVI", "LULC"] # Default
|
|
@@ -236,21 +301,14 @@ def build_multimodal_dataset(
|
|
| 236 |
urls = (os.path.join(path, split, majortom_mod, split_files["majortom"][split][0])
|
| 237 |
+ "::" + os.path.join(path, split, ssl4eos12_mod, split_files["ssl4eos12"][split][0]))
|
| 238 |
|
| 239 |
-
dataset =
|
| 240 |
-
return dataset
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
def build_datapipeline(urls, transform, batch_size, shuffle, return_metadata, *args, **kwargs):
|
| 244 |
-
shardshuffle = kwargs.get("shardshuffle", 100) * shuffle # Shuffle shard
|
| 245 |
-
deterministic = kwargs.get("deterministic", False)
|
| 246 |
-
seed = kwargs.get("seed", 0)
|
| 247 |
-
|
| 248 |
-
datapipeline = wds.DataPipeline(
|
| 249 |
# Infinitely sample shards from the shard list with replacement. Each worker is seeded independently.
|
| 250 |
(
|
| 251 |
-
wds.ResampledShards(urls, deterministic=deterministic, seed=seed)
|
| 252 |
if shuffle else wds.SimpleShardList(urls)
|
| 253 |
),
|
|
|
|
|
|
|
| 254 |
multi_tarfile_samples, # Extract individual samples from multi-modal tar files
|
| 255 |
wds.shuffle(shardshuffle, seed=seed), # Shuffle with a buffer of given size
|
| 256 |
(
|
|
@@ -271,7 +329,7 @@ def build_datapipeline(urls, transform, batch_size, shuffle, return_metadata, *a
|
|
| 271 |
else wds.map(identity)
|
| 272 |
),
|
| 273 |
)
|
| 274 |
-
return
|
| 275 |
|
| 276 |
|
| 277 |
def extract_modality_names(s):
|
|
@@ -308,7 +366,6 @@ def remove_extensions(sample):
|
|
| 308 |
|
| 309 |
def multi_tarfile_samples(
|
| 310 |
src_iter: Iterable[dict],
|
| 311 |
-
handler: Callable[[Exception], bool] = warn_and_continue,
|
| 312 |
):
|
| 313 |
"""
|
| 314 |
This function is adapted from https://github.com/apple/ml-4m/blob/main/fourm/data/unified_datasets.py.
|
|
@@ -329,7 +386,6 @@ def multi_tarfile_samples(
|
|
| 329 |
e.g. {"url": "shard_root_train_[rgb,caption]/00000.tar"}, {"url": "shard_root_train_[rgb,caption]/00001.tar"}, ...
|
| 330 |
This function will also work when no square braces for multiple modalities are used, e.g. {"url": "shard_root_train/00000.tar"}, ...
|
| 331 |
It can be a drop-in replacement for wds.tarfile_samples.
|
| 332 |
-
handler: Function that handles exceptions. If it returns True, the shard is skipped. If it returns False, the function exits.
|
| 333 |
|
| 334 |
Yields:
|
| 335 |
Dictionary of aligned samples from all modalities.
|
|
@@ -375,13 +431,9 @@ def multi_tarfile_samples(
|
|
| 375 |
yield merged_dict
|
| 376 |
|
| 377 |
except Exception as e:
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
print("Skipping shard...")
|
| 382 |
-
continue
|
| 383 |
-
else:
|
| 384 |
-
break
|
| 385 |
|
| 386 |
|
| 387 |
class Transpose(albumentations.ImageOnlyTransform):
|
|
@@ -410,7 +462,7 @@ class Transpose(albumentations.ImageOnlyTransform):
|
|
| 410 |
|
| 411 |
def default_non_image_transform(array):
|
| 412 |
if hasattr(array, "dtype") and (array.dtype == float or array.dtype == int):
|
| 413 |
-
return torch.from_numpy(array)
|
| 414 |
else:
|
| 415 |
return array
|
| 416 |
|
|
|
|
| 21 |
import re
|
| 22 |
import zarr
|
| 23 |
import torch
|
| 24 |
+
import warnings
|
| 25 |
import fsspec
|
| 26 |
import braceexpand
|
|
|
|
| 27 |
import albumentations
|
| 28 |
+
import numpy as np
|
| 29 |
import webdataset as wds
|
| 30 |
from collections.abc import Callable, Iterable
|
| 31 |
from torch.utils.data._utils.collate import default_collate
|
|
|
|
| 75 |
|
| 76 |
def build_terramesh_dataset(
|
| 77 |
path: str = "https://huggingface.co/datasets/ibm-esa-geospatial/TerraMesh/resolve/main/",
|
| 78 |
+
modalities: list[str] | str = None,
|
| 79 |
split: str = "val",
|
| 80 |
urls: str | None = None,
|
| 81 |
+
transform: Callable = None,
|
| 82 |
batch_size: int = 8,
|
| 83 |
return_metadata: bool = False,
|
| 84 |
shuffle: bool = True,
|
| 85 |
+
shardshuffle: int = 100,
|
| 86 |
+
deterministic: bool = False,
|
| 87 |
+
seed: int = None,
|
| 88 |
+
**kwargs,
|
| 89 |
):
|
| 90 |
+
"""
|
| 91 |
+
Builds a dataset for TerraMesh, see https://huggingface.co/datasets/ibm-esa-geospatial/TerraMesh.
|
| 92 |
+
|
| 93 |
+
:param path: URL or local path to dataset root that with data structure ./{split}/{modality}/shard_{id}.tar
|
| 94 |
+
:param modalities: List of modalities or a single modality name
|
| 95 |
+
:param split: Split name ("train", "val"). Default to "val".
|
| 96 |
+
:param urls: Specify custom shard urls instead of providing the path, modalities, and split.
|
| 97 |
+
:param batch_size: Specify batch size to load batches instead of samples via webdataset (Recommended).
|
| 98 |
+
It requires batch_size=None in the data loader constructor.
|
| 99 |
+
:param transform: Transform function to apply to the data, use MultimodalTransforms.
|
| 100 |
+
:param return_metadata: Load center coordinates, timestamp (ns as int) and cloud mask (if available).
|
| 101 |
+
:param shuffle: Shuffle samples and shards. Default to True.
|
| 102 |
+
:param shardshuffle: The number of shards to shuffle, or None. Defaults to 100.
|
| 103 |
+
:param deterministic: Whether to use deterministic shuffling. Defaults to False.
|
| 104 |
+
:param seed: Random seed for shuffling. Defaults to None which uses random seeds.
|
| 105 |
+
:param kwargs: Optional keyword arguments for single-modality which are passed to WebDataset constructor.
|
| 106 |
+
:return: WebDataset (single modality) or DataPipeline (multiple modalities)
|
| 107 |
+
"""
|
| 108 |
if len(modalities) == 1:
|
| 109 |
+
# Single modality
|
| 110 |
+
modalities = modalities[0]
|
| 111 |
+
|
| 112 |
+
if isinstance(modalities, str):
|
| 113 |
# Build standard WebDataset for single modality
|
| 114 |
dataset = build_wds_dataset(
|
| 115 |
path=path,
|
| 116 |
+
modality=modalities,
|
| 117 |
split=split,
|
| 118 |
urls=urls,
|
| 119 |
batch_size=batch_size,
|
| 120 |
+
transform=transform,
|
| 121 |
return_metadata=return_metadata,
|
| 122 |
shuffle=shuffle,
|
| 123 |
+
shardshuffle=shardshuffle,
|
| 124 |
+
deterministic=deterministic,
|
| 125 |
+
seed=seed,
|
| 126 |
+
**kwargs
|
| 127 |
)
|
| 128 |
return dataset
|
| 129 |
|
| 130 |
else:
|
| 131 |
+
if len(kwargs):
|
| 132 |
+
warnings.warn(f"keyword arguments ({kwargs}) are ignored for multiple modalities.")
|
| 133 |
+
|
| 134 |
# Build custom multi-modal dataset
|
| 135 |
dataset = build_multimodal_dataset(
|
| 136 |
path=path,
|
|
|
|
| 138 |
split=split,
|
| 139 |
urls=urls,
|
| 140 |
batch_size=batch_size,
|
| 141 |
+
transform=transform,
|
| 142 |
return_metadata=return_metadata,
|
| 143 |
shuffle=shuffle,
|
| 144 |
+
shardshuffle=shardshuffle,
|
| 145 |
+
deterministic=deterministic,
|
| 146 |
+
seed=seed,
|
| 147 |
)
|
| 148 |
return dataset
|
| 149 |
|
|
|
|
| 154 |
return zarr.open_consolidated(mapper, mode="r")["bands"][...]
|
| 155 |
|
| 156 |
|
| 157 |
+
# Default decoder
|
| 158 |
+
default_decoder = wds.decode()
|
| 159 |
+
|
| 160 |
+
|
| 161 |
def zarr_metadata_decoder(sample):
|
| 162 |
for key, value in list(sample.items()):
|
| 163 |
if key == "zarr.zip" or key.endswith(".zarr.zip"):
|
|
|
|
| 174 |
if data["time"][...] > 1e6: # DEM has no valid timestamp (value = 0)
|
| 175 |
time_key = "time" if key == "zarr.zip" else "time_" + key
|
| 176 |
sample[time_key] = data["time"][...] # Integer values of type "datetime64[ns]"
|
| 177 |
+
elif isinstance(value, str):
|
| 178 |
+
# Skip str data
|
| 179 |
+
pass
|
| 180 |
+
else:
|
| 181 |
+
# Fallback to webdataset autodecoder
|
| 182 |
+
sample[key] = next(wds.decode()([{key: value}]))[key]
|
| 183 |
|
| 184 |
return sample
|
| 185 |
|
|
|
|
| 212 |
transform: Callable = None,
|
| 213 |
shuffle: bool = True,
|
| 214 |
return_metadata: bool = False,
|
| 215 |
+
shardshuffle: int = 100,
|
| 216 |
+
deterministic: bool = False,
|
| 217 |
+
seed: int = None,
|
| 218 |
+
empty_check: bool = False,
|
| 219 |
*args, **kwargs
|
| 220 |
):
|
| 221 |
if urls is None:
|
|
|
|
| 232 |
[os.path.join(path, split, modality, f) for f in files]
|
| 233 |
)
|
| 234 |
|
| 235 |
+
if modality == "S1GRD" and split == "val" and empty_check:
|
| 236 |
+
# Setting empty_check to True to avoid errors because of a single shard file in SSL4EOS12 S1GRD val split
|
| 237 |
+
empty_check = False
|
| 238 |
|
| 239 |
# Build dataset
|
| 240 |
+
dataset = wds.WebDataset(
|
| 241 |
+
urls,
|
| 242 |
+
*args,
|
| 243 |
+
shardshuffle=shardshuffle * shuffle, # Shuffle shard
|
| 244 |
+
detshuffle=deterministic,
|
| 245 |
+
seed=seed,
|
| 246 |
+
handler=warn_and_continue,
|
| 247 |
+
nodesplitter=wds.split_by_node,
|
| 248 |
+
workersplitter=wds.split_by_worker,
|
| 249 |
+
empty_check=empty_check,
|
| 250 |
+
**kwargs
|
| 251 |
+
)
|
| 252 |
|
| 253 |
# Decode from bytes to numpy arrays, etc.
|
| 254 |
dataset = dataset.map(zarr_metadata_decoder) if return_metadata else dataset.decode(zarr_decoder)
|
|
|
|
| 278 |
transform: Callable = None,
|
| 279 |
shuffle: bool = True,
|
| 280 |
return_metadata: bool = False,
|
| 281 |
+
shardshuffle: int = 100,
|
| 282 |
+
deterministic: bool = False,
|
| 283 |
+
seed: int = None,
|
| 284 |
+
empty_check: bool = False,
|
| 285 |
):
|
| 286 |
if modalities is None:
|
| 287 |
modalities = ["S2L2A", "S2L1C", "S2RGB", "S1GRD", "S1RTC", "DEM", "NDVI", "LULC"] # Default
|
|
|
|
| 301 |
urls = (os.path.join(path, split, majortom_mod, split_files["majortom"][split][0])
|
| 302 |
+ "::" + os.path.join(path, split, ssl4eos12_mod, split_files["ssl4eos12"][split][0]))
|
| 303 |
|
| 304 |
+
dataset = wds.DataPipeline(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
# Infinitely sample shards from the shard list with replacement. Each worker is seeded independently.
|
| 306 |
(
|
| 307 |
+
wds.ResampledShards(urls, deterministic=deterministic, seed=seed, empty_check=empty_check)
|
| 308 |
if shuffle else wds.SimpleShardList(urls)
|
| 309 |
),
|
| 310 |
+
wds.split_by_node,
|
| 311 |
+
wds.split_by_worker,
|
| 312 |
multi_tarfile_samples, # Extract individual samples from multi-modal tar files
|
| 313 |
wds.shuffle(shardshuffle, seed=seed), # Shuffle with a buffer of given size
|
| 314 |
(
|
|
|
|
| 329 |
else wds.map(identity)
|
| 330 |
),
|
| 331 |
)
|
| 332 |
+
return dataset
|
| 333 |
|
| 334 |
|
| 335 |
def extract_modality_names(s):
|
|
|
|
| 366 |
|
| 367 |
def multi_tarfile_samples(
|
| 368 |
src_iter: Iterable[dict],
|
|
|
|
| 369 |
):
|
| 370 |
"""
|
| 371 |
This function is adapted from https://github.com/apple/ml-4m/blob/main/fourm/data/unified_datasets.py.
|
|
|
|
| 386 |
e.g. {"url": "shard_root_train_[rgb,caption]/00000.tar"}, {"url": "shard_root_train_[rgb,caption]/00001.tar"}, ...
|
| 387 |
This function will also work when no square braces for multiple modalities are used, e.g. {"url": "shard_root_train/00000.tar"}, ...
|
| 388 |
It can be a drop-in replacement for wds.tarfile_samples.
|
|
|
|
| 389 |
|
| 390 |
Yields:
|
| 391 |
Dictionary of aligned samples from all modalities.
|
|
|
|
| 431 |
yield merged_dict
|
| 432 |
|
| 433 |
except Exception as e:
|
| 434 |
+
warnings.warn(f"Exception occurred while processing {src['url']}: {repr(e)}."
|
| 435 |
+
f"Skipping shard")
|
| 436 |
+
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
| 437 |
|
| 438 |
|
| 439 |
class Transpose(albumentations.ImageOnlyTransform):
|
|
|
|
| 462 |
|
| 463 |
def default_non_image_transform(array):
|
| 464 |
if hasattr(array, "dtype") and (array.dtype == float or array.dtype == int):
|
| 465 |
+
return torch.from_numpy(array.copy())
|
| 466 |
else:
|
| 467 |
return array
|
| 468 |
|