Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

deadtreedata.py 13 KB

You have to be logged in to leave a comment. Sign In
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
  1. import io
  2. import logging
  3. import math
  4. from collections.abc import Iterable
  5. from functools import partial
  6. from pathlib import Path
  7. from typing import Callable, Dict, List, Optional, Union
  8. import albumentations as A
  9. import webdataset as wds
  10. from albumentations.pytorch import ToTensorV2
  11. import numpy as np
  12. import omegaconf
  13. import PIL
  14. import pytorch_lightning as pl
  15. import torch
  16. from deadtrees.loss.losses import class2one_hot, one_hot2dist
  17. from omegaconf import DictConfig, OmegaConf
  18. from pytorch_lightning.trainer.supporters import CombinedLoader
  19. from torch.utils.data import DataLoader
  20. logger = logging.getLogger(__name__)
  21. # NOTE: mean ans std computed on train shards
  22. class DeadtreeDatasetConfig:
  23. """Dataset configuration"""
  24. # stats based on years 2017, 2018, 2019, 2020 and subtiles subsampled for 0.1
  25. mean = np.array([0.3661029729, 0.3875165941, 0.3501133538, 0.5797285859])
  26. std = np.array([0.2388708549, 0.2103625723, 0.2050272174, 0.2025812523])
  27. tile_size = 256
  28. fractions = [0.7, 0.2, 0.1]
  29. class DeadtreeDatasetConfigImagenet:
  30. """Dataset configuration (imagenet pretrained encoder)"""
  31. # NIR channel info same as red
  32. mean = np.array([0.485, 0.456, 0.406, 0.485])
  33. std = np.array([0.229, 0.224, 0.225, 0.229])
  34. tile_size = 256
  35. fractions = [0.7, 0.2, 0.1]
  36. def split_shards(original_list, split_fractions):
  37. """Distribute shards into train/ valid/ test sets according to provided split ratios"""
  38. assert np.isclose(
  39. sum(split_fractions), 1.0
  40. ), f"Split fractions do not sum to 1: {sum(split_fractions)}"
  41. original_list = [str(x) for x in sorted(original_list)]
  42. sublists = []
  43. prev_index = 0
  44. for weight in split_fractions:
  45. next_index = prev_index + int(round((len(original_list) * weight), 0))
  46. sublists.append(original_list[prev_index:next_index])
  47. prev_index = next_index
  48. assert sum([len(x) for x in sublists]) == len(original_list), "Split size mismatch"
  49. if not all(len(x) > 0 for x in sublists):
  50. logger.warning("Unexpected shard distribution encountered - trying to fix this")
  51. if len(split_fractions) == 3:
  52. if len(sublists[0]) > 2:
  53. sublists[0] = original_list[:-2]
  54. sublists[1] = original_list[-2:-1]
  55. sublists[2] = original_list[-1:]
  56. else:
  57. raise ValueError(
  58. f"Not enough shards (#{len(original_list)}) for new distribution"
  59. )
  60. elif len(split_fractions) == 2:
  61. sublists[0] = original_list[:-1]
  62. sublists[1] = original_list[-1:]
  63. else:
  64. raise ValueError
  65. logger.warning(f"New shard split: {sublists}")
  66. if len(sublists) != 3:
  67. logger.warning("No test shards specified")
  68. sublists.append(None)
  69. return sublists
  70. def image_decoder(data):
  71. with io.BytesIO(data) as stream:
  72. img = PIL.Image.open(stream)
  73. img.load()
  74. img = img.convert("RGBA")
  75. return np.asarray(img)
  76. def mask_decoder(data):
  77. with io.BytesIO(data) as stream:
  78. img = PIL.Image.open(stream)
  79. img.load()
  80. img = img.convert("L")
  81. return np.asarray(img)
  82. def sample_decoder(
  83. sample, img_suffix="rgbn.tif", msk_suffix="mask.tif", lu_suffix="lu.tif"
  84. ):
  85. """Decode data (image, mask, lu, stats) from sharded datastore"""
  86. assert img_suffix in sample, "Wrong image suffix provided"
  87. sample[img_suffix] = image_decoder(sample[img_suffix])
  88. if "txt" in sample:
  89. sample["txt"] = {"file": sample["__key__"], "frac": float(sample["txt"])}
  90. if msk_suffix in sample:
  91. sample[msk_suffix] = mask_decoder(sample[msk_suffix])
  92. if lu_suffix in sample:
  93. sample[lu_suffix] = mask_decoder(sample[lu_suffix])
  94. return sample
  95. def inv_normalize(x):
  96. return lambda x: x * DeadtreeDatasetConfig.std + DeadtreeDatasetConfig.mean
  97. train_transform = A.Compose(
  98. [
  99. # A.Resize(256,256),
  100. A.OneOf([A.HorizontalFlip(), A.VerticalFlip()], p=0.5),
  101. A.RandomRotate90(p=0.5),
  102. A.RandomBrightnessContrast(
  103. p=0.5,
  104. brightness_limit=0.2,
  105. contrast_limit=0.15,
  106. brightness_by_max=False,
  107. ),
  108. A.Normalize(mean=DeadtreeDatasetConfig.mean, std=DeadtreeDatasetConfig.std),
  109. ToTensorV2(),
  110. ]
  111. )
  112. val_transform = A.Compose(
  113. [
  114. # A.Resize(256,256),
  115. A.Normalize(mean=DeadtreeDatasetConfig.mean, std=DeadtreeDatasetConfig.std),
  116. ToTensorV2(),
  117. ]
  118. )
  119. def transform(
  120. sample: dict,
  121. *,
  122. transform_func: Optional[Callable] = None,
  123. in_channels: Optional[int] = 4,
  124. classes: Optional[int] = 3,
  125. distmap: Optional[bool] = False,
  126. ):
  127. """Apply transform func to sample and modify channels and/ or classes as specified in training setup"""
  128. if transform_func:
  129. transformed = transform_func(
  130. image=sample["image"].copy(),
  131. mask=sample["mask"].copy(),
  132. lu=sample["lu"].copy(),
  133. )
  134. sample["image"] = transformed["image"].float()
  135. sample["mask"] = transformed["mask"].long()
  136. sample["lu"] = transformed["lu"]
  137. sample["image"] = sample["image"][0:in_channels]
  138. sample["lu"] = torch.tensor(sample["lu"], dtype=torch.long)
  139. if classes == 2:
  140. sample["mask"][sample["mask"] > 1] = 1
  141. if distmap:
  142. x = class2one_hot(torch.unsqueeze(sample["mask"], dim=0), K=classes)[0]
  143. x = one_hot2dist(x.cpu().numpy(), resolution=[1, 1])
  144. sample["distmap"] = torch.tensor(x, dtype=torch.float32)
  145. else:
  146. sample["distmap"] = None
  147. return sample
  148. class DeadtreesDataModule(pl.LightningDataModule):
  149. def __init__(
  150. self,
  151. data_dir: Union[List, str],
  152. pattern: str,
  153. pattern_extra: Optional[List[str]] = None,
  154. batch_size_extra: Optional[List[int]] = None,
  155. train_dataloader_conf: Optional[DictConfig] = None,
  156. val_dataloader_conf: Optional[DictConfig] = None,
  157. test_dataloader_conf: Optional[DictConfig] = None,
  158. ):
  159. super().__init__()
  160. print(type(data_dir))
  161. print(data_dir)
  162. if isinstance(data_dir, Iterable):
  163. self.data_shards = [sorted(Path(d).glob(pattern)) for d in data_dir]
  164. self.layout = "train/val/test"
  165. else:
  166. self.data_shards = sorted(Path(data_dir).glob(pattern))
  167. self.layout = "single_directory"
  168. self.train_dataloader_conf = train_dataloader_conf or OmegaConf.create()
  169. self.val_dataloader_conf = val_dataloader_conf or OmegaConf.create()
  170. self.test_dataloader_conf = test_dataloader_conf or OmegaConf.create()
  171. self.data_shards_extra = []
  172. self.batch_size_extra = []
  173. if pattern_extra and batch_size_extra:
  174. if self.layout == "train/val/test":
  175. raise ValueError(
  176. "Combining pattern_extra with train/val/test layout not allowed"
  177. )
  178. for pcnt, p in enumerate(pattern_extra):
  179. self.data_shards_extra.append(sorted(Path(data_dir).glob(p)))
  180. if len(batch_size_extra) > 0:
  181. if len(batch_size_extra) != len(pattern_extra):
  182. raise ValueError(
  183. "Len of <pattern_extra> and <batch_size_extra> don't match"
  184. )
  185. self.batch_size_extra = batch_size_extra
  186. else:
  187. raise ValueError(
  188. "<pattern_extra> provided but no <batch_size_extra> ratio found"
  189. )
  190. def setup(
  191. self,
  192. stage=None, # required for 1.6
  193. split_fractions: List[float] = DeadtreeDatasetConfig.fractions,
  194. in_channels: Optional[int] = 4, # change to 3 for rgb training instead of rgbn
  195. classes: Optional[int] = 3, # change to 2 for single class (+bg) setup
  196. ) -> None:
  197. if self.layout == "single_directory":
  198. train_shards, valid_shards, test_shards = split_shards(
  199. self.data_shards, split_fractions
  200. )
  201. else:
  202. train_shards, valid_shards, test_shards = self.data_shards
  203. train_shards = [str(x) for x in train_shards]
  204. valid_shards = [str(x) for x in valid_shards]
  205. test_shards = [str(x) for x in test_shards]
  206. # determine the length of the dataset
  207. shard_size = sum(1 for _ in DataLoader(wds.WebDataset(train_shards[0])))
  208. logger.info(
  209. f"Shard size: {shard_size} (estimate base on file: {train_shards[0]})"
  210. )
  211. def build_dataset(
  212. shards: List[str],
  213. bs: int,
  214. transform_func: Callable,
  215. shuffle: Optional[int] = 128,
  216. shard_size: Optional[int] = 128,
  217. ) -> wds.WebDataset:
  218. return (
  219. wds.WebDataset(
  220. shards,
  221. length=len(shards) * shard_size // bs,
  222. )
  223. .shuffle(shuffle)
  224. .map(sample_decoder)
  225. .rename(image="rgbn.tif", mask="mask.tif", lu="lu.tif", stats="txt")
  226. .map(
  227. partial(
  228. transform,
  229. transform_func=transform_func,
  230. in_channels=in_channels,
  231. classes=classes,
  232. distmap=True,
  233. )
  234. )
  235. .to_tuple("image", "mask", "distmap", "lu", "stats")
  236. )
  237. self.train_data = build_dataset(
  238. train_shards,
  239. self.train_dataloader_conf["batch_size"],
  240. transform_func=train_transform,
  241. shuffle=shard_size,
  242. shard_size=shard_size,
  243. )
  244. self.val_data = build_dataset(
  245. valid_shards,
  246. self.val_dataloader_conf["batch_size"],
  247. transform_func=val_transform,
  248. shuffle=0,
  249. shard_size=shard_size,
  250. )
  251. if test_shards:
  252. self.test_data = build_dataset(
  253. test_shards,
  254. self.test_dataloader_conf["batch_size"],
  255. transform_func=val_transform,
  256. shuffle=0,
  257. shard_size=shard_size,
  258. )
  259. self.extra_train_data = []
  260. self.extra_valid_data = []
  261. if len(self.data_shards_extra) > 0:
  262. for bs, shards in zip(self.batch_size_extra, self.data_shards_extra):
  263. # split shards between train and val by the same proportion as the main dataset
  264. train_frac = len(train_shards) / (len(train_shards) + len(valid_shards))
  265. valid_frac = 1 - train_frac
  266. extra_train_shards, extra_valid_shards, _ = split_shards(
  267. shards, [train_frac, valid_frac]
  268. )
  269. self.extra_train_data.append(
  270. build_dataset(
  271. extra_train_shards,
  272. bs,
  273. transform_func=train_transform,
  274. shuffle=shard_size,
  275. shard_size=shard_size,
  276. )
  277. )
  278. self.extra_valid_data.append(
  279. build_dataset(
  280. extra_valid_shards,
  281. bs,
  282. transform_func=val_transform,
  283. shuffle=0,
  284. shard_size=shard_size,
  285. )
  286. )
  287. def train_dataloader(self) -> Dict[str, DataLoader]:
  288. main_loader = DataLoader(
  289. self.train_data.batched(
  290. self.train_dataloader_conf["batch_size"] - sum(self.batch_size_extra),
  291. partial=False,
  292. ),
  293. batch_size=None,
  294. pin_memory=False,
  295. num_workers=self.train_dataloader_conf["num_workers"],
  296. )
  297. loaders = {"main": main_loader}
  298. for cnt, (bs, train_data) in enumerate(
  299. zip(self.batch_size_extra, self.extra_train_data)
  300. ):
  301. loaders[f"extra_{cnt}"] = DataLoader(
  302. train_data.batched(bs, partial=False),
  303. batch_size=None,
  304. pin_memory=True,
  305. num_workers=bs // 2,
  306. )
  307. return loaders
  308. def val_dataloader(self) -> List[DataLoader]:
  309. main_loader = DataLoader(
  310. self.val_data.batched(
  311. self.val_dataloader_conf["batch_size"] - sum(self.batch_size_extra),
  312. partial=False,
  313. ),
  314. batch_size=None,
  315. pin_memory=False,
  316. num_workers=self.val_dataloader_conf["num_workers"],
  317. )
  318. loaders = {"main": main_loader}
  319. for cnt, (bs, val_data) in enumerate(
  320. zip(self.batch_size_extra, self.extra_valid_data)
  321. ):
  322. loaders[f"extra_{cnt}"] = DataLoader(
  323. val_data.batched(bs, partial=False),
  324. batch_size=None,
  325. pin_memory=True,
  326. num_workers=bs // 2,
  327. )
  328. combined_loaders = CombinedLoader(loaders, "max_size_cycle")
  329. return combined_loaders
  330. def test_dataloader(self) -> DataLoader:
  331. return DataLoader(
  332. self.test_data.batched(
  333. self.test_dataloader_conf["batch_size"], partial=False
  334. ),
  335. batch_size=None,
  336. pin_memory=False,
  337. num_workers=self.test_dataloader_conf["num_workers"],
  338. )
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...