-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata.py
207 lines (183 loc) · 6.39 KB
/
data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import logging
import math
import random
import webdataset as wds
from webdataset import WebLoader
from transforms import image_transform
logger = logging.getLogger(__name__)
_SHARD_SHUFFLE_SIZE = 2000
_SHARD_SHUFFLE_INITIAL = 500
_SAMPLE_SHUFFLE_SIZE = 5000
_SAMPLE_SHUFFLE_INITIAL = 1000
def get_webdataset(
cfg, dataset, split, clip_transform, clip_normalization=False, tokenizer=None
) -> WebLoader:
def _read_wds_info(path, split):
info = dict()
with open(f"{path}/classnames.txt", "r") as f:
info["classnames"] = f.read().splitlines()
with open(f"{path}/zeroshot_classification_templates.txt", "r") as f:
info["templates"] = f.read().splitlines()
with open(f"{path}/{split}/nshards.txt", "r") as f:
info["num_shards"] = int(f.read().splitlines()[0])
with open(f"{path}/{split}/nsamples.txt", "r") as f:
info["num_samples"] = int(f.read().splitlines()[0])
return info
is_train = split == "train"
round_fn = math.floor if is_train else math.ceil
wds_info = _read_wds_info(dataset["path"], split)
if cfg["task"]["id"] == "patch":
transform = image_transform(
modality=dataset["modality"],
clip_transform=clip_transform,
clip_normalization=clip_normalization,
use_augmentations=is_train,
)
elif cfg["task"]["id"] == "align":
satellite, product_type = dataset["modality"].split("_")
transform_rgb = image_transform(
modality=f"RGB_{product_type}",
clip_transform=clip_transform,
clip_normalization=clip_normalization,
)
# TODO: check S1_RGB use case
transform_ms = image_transform(
modality=f"{satellite}_{product_type}",
clip_transform=clip_transform,
)
else:
raise ValueError(f"Unknown task {cfg['task']}")
if cfg["is_distributed"] and is_train:
global_batch_size = cfg["task"][f"{split}_batch_size"] * cfg.world_size
num_batches = round_fn(wds_info["num_samples"] / global_batch_size)
num_worker_batches = round_fn(num_batches / cfg.num_workers)
num_batches = num_worker_batches * cfg.num_workers
num_samples = num_batches * global_batch_size
pipeline = [
wds.ResampledShards(
"/".join(
[
dataset["path"],
split,
f"{{0..{wds_info['num_shards']-1}}}.{'tar.gz' if dataset['compressed'] else 'tar'}",
]
)
),
]
else:
num_batches = round_fn(
wds_info["num_samples"] / cfg["task"][f"{split}_batch_size"]
)
num_samples = num_batches * cfg["task"][f"{split}_batch_size"]
pipeline = [
wds.SimpleShardList(
"/".join(
[
dataset["path"],
split,
f"{{0..{wds_info['num_shards']-1}}}.{'tar.gz' if dataset['compressed'] else 'tar'}",
]
),
seed=cfg["torch"]["seed"],
),
]
if is_train and cfg["task"]["shuffle"] and not cfg["is_distributed"]:
pipeline.append(
wds.detshuffle(
bufsize=_SHARD_SHUFFLE_SIZE,
initial=_SHARD_SHUFFLE_INITIAL,
seed=cfg["torch"]["seed"],
),
)
if not cfg["is_distributed"]:
pipeline.extend(
[
wds.split_by_worker,
wds.tarfile_to_samples(),
]
)
else:
pipeline.append(
wds.tarfile_to_samples(),
)
if is_train and cfg["task"]["shuffle"]:
pipeline.append(
wds.detshuffle(
bufsize=_SAMPLE_SHUFFLE_SIZE,
initial=_SAMPLE_SHUFFLE_INITIAL,
seed=cfg["torch"]["seed"],
),
)
if cfg["task"]["id"] == "patch":
pipeline.extend(
[
wds.decode("pil"),
wds.rename(
image=dataset["image_key"],
label=dataset["target_key"],
),
]
)
if tokenizer:
pipeline.append(
wds.map_dict(
image=transform, label=lambda target: tokenizer(target)[0]
),
),
else:
pipeline.extend(
[
wds.map_dict(image=transform),
wds.to_tuple("image", "label"),
]
)
elif cfg["task"]["id"] == "align":
pipeline.extend(
[
wds.decode(),
wds.rename(
image_rgb=dataset["image_key"],
image_ms=dataset["image_key"],
label=dataset["target_key"],
),
wds.map_dict(
image_rgb=transform_rgb,
image_ms=transform_ms,
),
wds.to_tuple("image_rgb", "image_ms", "label"),
]
)
pipeline.append(
wds.batched(
(
cfg["task"][f"{split}_batch_size"] // cfg["torch"]["num_workers"]
if cfg["torch"]["num_workers"]
else cfg["task"][f"{split}_batch_size"]
),
partial=not is_train,
),
)
ds = wds.DataPipeline(*pipeline).with_length(wds_info["num_samples"])
dataloader = WebLoader(
dataset=ds,
batch_size=None,
shuffle=False,
num_workers=cfg["torch"]["num_workers"],
persistent_workers=cfg["torch"]["num_workers"] > 0 if is_train else False,
pin_memory=True,
)
if is_train and cfg["task"]["id"] == "patch":
dataloader = (
dataloader.unbatched()
.shuffle(_SAMPLE_SHUFFLE_SIZE, rng=random.Random(cfg["torch"]["seed"]))
.batched(cfg["task"][f"{split}_batch_size"])
)
else:
dataloader = dataloader.unbatched().batched(cfg["task"][f"{split}_batch_size"])
dataloader.with_epoch(num_batches)
dataloader.name = dataset["id"]
dataloader.classnames = wds_info["classnames"]
dataloader.templates = wds_info["templates"]
dataloader.num_batches = num_batches
dataloader.num_samples = num_samples
return dataloader