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

test_data_adapters.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
  1. import unittest
  2. import numpy as np
  3. import torch
  4. from torch.utils.data import Dataset
  5. from torch.utils.data import DataLoader
  6. from data_gradients.managers.detection_manager import DetectionAnalysisManager
  7. from data_gradients.managers.segmentation_manager import SegmentationAnalysisManager
  8. from data_gradients.managers.classification_manager import ClassificationAnalysisManager
  9. from super_gradients.training.utils.collate_fn import (
  10. DetectionDatasetAdapterCollateFN,
  11. SegmentationDatasetAdapterCollateFN,
  12. ClassificationDatasetAdapterCollateFN,
  13. )
  14. class SimpleDataset(Dataset):
  15. def __init__(self, images, labels):
  16. self.images = images
  17. self.labels = labels
  18. def __len__(self):
  19. return len(self.images)
  20. def __getitem__(self, idx):
  21. return self.images[idx], self.labels[idx]
  22. def generate_masks(pattern_num):
  23. onehot_mask = torch.zeros((6, 640, 540), dtype=torch.uint8)
  24. if pattern_num == 0:
  25. onehot_mask[0, :213, :] = 1
  26. onehot_mask[1, 213:426, :] = 1
  27. onehot_mask[2, 426:, :] = 1
  28. elif pattern_num == 1:
  29. onehot_mask[3, :213, :] = 1
  30. onehot_mask[4, 213:426, :] = 1
  31. onehot_mask[5, 426:, :] = 1
  32. elif pattern_num == 2:
  33. for i in range(6):
  34. onehot_mask[i, i * 106 : (i + 1) * 106, i * 90 : (i + 1) * 90] = 1
  35. return onehot_mask
  36. class TestDetectionAdapter(unittest.TestCase):
  37. def setUp(self) -> None:
  38. _source_targets = [
  39. np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]),
  40. np.array([[10, 20, 10, 10, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]),
  41. np.array([[30, 30, 10, 10, 2], [50, 50, 10, 10, 3], [0, 0, 0, 0, 0]]),
  42. np.array([[70, 70, 10, 10, 4], [80, 80, 10, 10, 5], [0, 0, 0, 0, 0]]),
  43. np.array([[50, 50, 10, 10, 2], [60, 70, 10, 10, 4], [30, 30, 10, 10, 1]]),
  44. ]
  45. _source_images = [np.random.randint(low=0, high=255, size=(3, 640, 540)) for _ in range(len(_source_targets))]
  46. self.dataset = SimpleDataset(images=_source_images, labels=_source_targets)
  47. # (N, 6) [sample_i, label, CX, CY, W, H)
  48. self.expected_targets_batches = [
  49. torch.tensor([[1, 1, 15, 25, 10, 10]]),
  50. torch.tensor([[0, 2, 35, 35, 10, 10], [0, 3, 55, 55, 10, 10], [1, 4, 75, 75, 10, 10], [1, 5, 85, 85, 10, 10]]),
  51. torch.tensor([[0, 2, 55, 55, 10, 10], [0, 4, 65, 75, 10, 10], [0, 1, 35, 35, 10, 10]]),
  52. ]
  53. self.expected_image_shapes_batches = [
  54. torch.Size([2, 3, 640, 540]),
  55. torch.Size([2, 3, 640, 540]),
  56. torch.Size([1, 3, 640, 540]),
  57. ]
  58. def test_adapt_dataset_detection(self):
  59. analyzer_ds = DetectionAnalysisManager(
  60. report_title="test_adapt_dataset_detection",
  61. train_data=self.dataset,
  62. val_data=self.dataset,
  63. class_names=list(map(str, range(6))),
  64. use_cache=True,
  65. is_label_first=False,
  66. bbox_format="xywh",
  67. )
  68. analyzer_ds.run() # Run the analysis. This will create the cache.
  69. loader = DataLoader(self.dataset, batch_size=2, collate_fn=DetectionDatasetAdapterCollateFN(config_path=analyzer_ds.config.cache_path, n_classes=6))
  70. for expected_images_shape, expected_targets, (images, targets) in zip(self.expected_image_shapes_batches, self.expected_targets_batches, loader):
  71. self.assertEqual(images.shape, expected_images_shape)
  72. self.assertTrue(((0 <= images) & (images <= 255)).all()) # Should be 0-255
  73. self.assertTrue(torch.equal(targets, expected_targets))
  74. def test_overriding_collate_detection(self):
  75. loader = DataLoader(self.dataset, batch_size=2)
  76. analyzer_ds = DetectionAnalysisManager(
  77. report_title="test_overriding_collate_detection",
  78. train_data=loader,
  79. val_data=loader,
  80. class_names=list(map(str, range(6))),
  81. use_cache=True,
  82. is_label_first=False,
  83. bbox_format="xywh",
  84. )
  85. analyzer_ds.run() # Run the analysis. This will create the cache.
  86. loader.collate_fn = DetectionDatasetAdapterCollateFN(collate_fn=loader.collate_fn, config_path=analyzer_ds.config.cache_path, n_classes=6)
  87. for expected_images_shape, expected_targets, (images, targets) in zip(self.expected_image_shapes_batches, self.expected_targets_batches, loader):
  88. self.assertEqual(images.shape, expected_images_shape)
  89. self.assertTrue(((0 <= images) & (images <= 255)).all()) # Should be 0-255
  90. self.assertTrue(torch.equal(targets, expected_targets))
  91. def test_adapt_dataloader_detection(self):
  92. loader = DataLoader(self.dataset, batch_size=2)
  93. analyzer_ds = DetectionAnalysisManager(
  94. report_title="test_adapt_dataloader_detection",
  95. train_data=loader,
  96. val_data=loader,
  97. class_names=list(map(str, range(6))),
  98. use_cache=True,
  99. is_label_first=False,
  100. bbox_format="xywh",
  101. )
  102. analyzer_ds.run()
  103. loader = DetectionDatasetAdapterCollateFN.adapt_dataloader(dataloader=loader, config_path=analyzer_ds.config.cache_path, n_classes=6)
  104. for expected_images_shape, expected_targets, (images, targets) in zip(self.expected_image_shapes_batches, self.expected_targets_batches, loader):
  105. self.assertEqual(images.shape, expected_images_shape)
  106. self.assertTrue(((0 <= images) & (images <= 255)).all()) # Should be 0-255
  107. self.assertTrue(torch.equal(targets, expected_targets))
  108. class TestSegmentationAdapter(unittest.TestCase):
  109. def setUp(self) -> None:
  110. _source_masks_onehot = [generate_masks(i) for i in range(3)]
  111. _source_images = [np.random.randint(low=0, high=255, size=(3, 640, 540), dtype=np.uint8) for _ in range(len(_source_masks_onehot))]
  112. self.dataset = SimpleDataset(images=_source_images, labels=_source_masks_onehot)
  113. # Expected masks in categorical format
  114. self.expected_masks_batches = [
  115. torch.cat([_source_masks_onehot[0].argmax(0).unsqueeze(0), _source_masks_onehot[1].argmax(0).unsqueeze(0)], dim=0),
  116. torch.cat([_source_masks_onehot[2].argmax(0).unsqueeze(0)], dim=0),
  117. ]
  118. self.expected_image_shapes_batches = [
  119. torch.Size([2, 3, 640, 540]),
  120. torch.Size([1, 3, 640, 540]),
  121. ]
  122. def test_adapt_dataset_segmentation(self):
  123. analyzer_ds = SegmentationAnalysisManager(
  124. report_title="test_adapt_dataset_segmentation",
  125. train_data=self.dataset,
  126. val_data=self.dataset,
  127. class_names=list(map(str, range(6))),
  128. use_cache=True,
  129. is_batch=False,
  130. )
  131. analyzer_ds.run()
  132. loader = DataLoader(self.dataset, batch_size=2, collate_fn=SegmentationDatasetAdapterCollateFN(config_path=analyzer_ds.config.cache_path, n_classes=6))
  133. for expected_images_shape, expected_masks, (images, masks) in zip(self.expected_image_shapes_batches, self.expected_masks_batches, loader):
  134. self.assertEqual(images.shape, expected_images_shape)
  135. self.assertTrue((masks == expected_masks).all()) # Checking that the masks are as expected
  136. def test_overriding_collate_segmentation(self):
  137. loader = DataLoader(self.dataset, batch_size=2)
  138. # Run the analysis on DATALOADER
  139. analyzer_ds = SegmentationAnalysisManager(
  140. report_title="test_overriding_collate_segmentation",
  141. train_data=loader,
  142. val_data=loader,
  143. class_names=list(map(str, range(6))),
  144. use_cache=True,
  145. is_batch=True,
  146. )
  147. analyzer_ds.run()
  148. loader.collate_fn = SegmentationDatasetAdapterCollateFN(base_collate_fn=loader.collate_fn, config_path=analyzer_ds.config.cache_path, n_classes=6)
  149. for expected_images_shape, expected_masks, (images, masks) in zip(self.expected_image_shapes_batches, self.expected_masks_batches, loader):
  150. self.assertEqual(images.shape, expected_images_shape)
  151. self.assertTrue((masks == expected_masks).all()) # Checking that the masks are as expected
  152. def test_adapt_dataloader_segmentation(self):
  153. loader = DataLoader(self.dataset, batch_size=2)
  154. analyzer_ds = SegmentationAnalysisManager(
  155. report_title="test_adapt_dataloader_segmentation",
  156. train_data=loader,
  157. val_data=loader,
  158. class_names=list(map(str, range(6))),
  159. use_cache=True,
  160. is_batch=True,
  161. )
  162. analyzer_ds.run()
  163. # This is required to use the adapter inside the existing Dataloader.
  164. loader = SegmentationDatasetAdapterCollateFN.adapt_dataloader(dataloader=loader, config_path=analyzer_ds.config.cache_path, n_classes=6)
  165. for expected_images_shape, expected_masks, (images, masks) in zip(self.expected_image_shapes_batches, self.expected_masks_batches, loader):
  166. self.assertEqual(images.shape, expected_images_shape)
  167. self.assertTrue((masks == expected_masks).all()) # Checking that the masks are as expected
  168. class TestClassificationAdapter(unittest.TestCase):
  169. def setUp(self) -> None:
  170. # 0 or 1 labels for this simple example
  171. _source_labels = np.array([0, 1, 0, 1, 0])
  172. _source_images = [np.random.randint(low=0, high=255, size=(3, 640, 540)) for _ in range(len(_source_labels))]
  173. self.dataset = SimpleDataset(images=_source_images, labels=_source_labels)
  174. self.expected_labels_batches = [torch.tensor([0, 1]), torch.tensor([0, 1]), torch.tensor([0])]
  175. self.expected_image_shapes_batches = [
  176. torch.Size([2, 3, 640, 540]),
  177. torch.Size([2, 3, 640, 540]),
  178. torch.Size([1, 3, 640, 540]),
  179. ]
  180. def test_adapt_dataset_classification(self):
  181. analyzer_ds = ClassificationAnalysisManager(
  182. report_title="test_adapt_dataset_classification",
  183. train_data=self.dataset,
  184. val_data=self.dataset,
  185. class_names=list(map(str, range(6))),
  186. images_extractor="[0]",
  187. labels_extractor="[1]",
  188. use_cache=True,
  189. is_batch=False,
  190. )
  191. analyzer_ds.run()
  192. loader = DataLoader(
  193. self.dataset, batch_size=2, collate_fn=ClassificationDatasetAdapterCollateFN(config_path=analyzer_ds.config.cache_path, n_classes=6)
  194. )
  195. for expected_images_shape, expected_labels, (images, labels) in zip(self.expected_image_shapes_batches, self.expected_labels_batches, loader):
  196. self.assertEqual(images.shape, expected_images_shape)
  197. self.assertTrue(torch.equal(labels, expected_labels))
  198. def test_adapt_dataloader_override_collate_classification(self):
  199. loader = DataLoader(self.dataset, batch_size=2)
  200. analyzer_ds = ClassificationAnalysisManager(
  201. report_title="test_adapt_dataloader_override_collate_classification",
  202. train_data=loader,
  203. val_data=loader,
  204. class_names=list(map(str, range(6))),
  205. images_extractor="[0]",
  206. labels_extractor="[1]",
  207. use_cache=True,
  208. is_batch=True,
  209. )
  210. analyzer_ds.run()
  211. # This is required to use the adapter inside the existing Dataloader.
  212. # `base_collate_fn=loader.base_collate_fn` ensure to still take into account any collate_fn that was passed to the Dataloader
  213. loader.collate_fn = ClassificationDatasetAdapterCollateFN(base_collate_fn=loader.collate_fn, config_path=analyzer_ds.config.cache_path, n_classes=6)
  214. for expected_images_shape, expected_labels, (images, labels) in zip(self.expected_image_shapes_batches, self.expected_labels_batches, loader):
  215. self.assertEqual(images.shape, expected_images_shape)
  216. self.assertTrue(torch.equal(labels, expected_labels))
  217. def test_adapt_dataloader_classification(self):
  218. loader = DataLoader(self.dataset, batch_size=2)
  219. analyzer_ds = ClassificationAnalysisManager(
  220. report_title="test_adapt_dataloader_classification",
  221. train_data=loader,
  222. val_data=loader,
  223. class_names=list(map(str, range(6))),
  224. images_extractor="[0]",
  225. labels_extractor="[1]",
  226. use_cache=True,
  227. is_batch=True,
  228. )
  229. analyzer_ds.run()
  230. # This is required to use the adapter inside the existing Dataloader.
  231. loader = ClassificationDatasetAdapterCollateFN.adapt_dataloader(dataloader=loader, config_path=analyzer_ds.config.cache_path, n_classes=6)
  232. for expected_images_shape, expected_labels, (images, labels) in zip(self.expected_image_shapes_batches, self.expected_labels_batches, loader):
  233. self.assertEqual(images.shape, expected_images_shape)
  234. self.assertTrue(torch.equal(labels, expected_labels))
  235. if __name__ == "__main__":
  236. unittest.main()
Tip!

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

Comments

Loading...