-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprepare_data.py
executable file
·233 lines (191 loc) · 8.02 KB
/
prepare_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
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
import torch
from torch.utils.data import DistributedSampler
from typing import List
import os
import numpy as np
from ffcv.pipeline.operation import Operation
from ffcv.loader import Loader, OrderOption
from rand_augment import RandomAugment
from ffcv.transforms import ToTensor, ToDevice, Squeeze, NormalizeImage, RandomHorizontalFlip, ToTorchImage
from ffcv.fields.rgb_image import CenterCropRGBImageDecoder, RandomResizedCropRGBImageDecoder
from ffcv.fields.basics import IntDecoder
from distributed_utils import is_main_process
from ffcv.traversal_order.base import TraversalOrder
IMAGENET_MEAN = np.array([0.485, 0.456, 0.406]) * 255
IMAGENET_STD = np.array([0.229, 0.224, 0.225]) * 255
DEFAULT_CROP_RATIO = 224/256
from typing import Sequence
import numpy as np
from torch.utils.data import DistributedSampler
class XRandom(TraversalOrder):
def __init__(self, loader:'Loader'):
super().__init__(loader)
self.rank = int(os.environ["RANK"])
self.world_size = int(os.environ['WORLD_SIZE'])
if self.distributed:
self.sampler = DistributedSampler(self.indices,
num_replicas=self.world_size,
rank=self.rank,
shuffle=True,
seed=self.seed,
drop_last=False)
def sample_order(self, epoch: int) -> Sequence[int]:
if not self.distributed:
generator = np.random.default_rng(self.seed + epoch if self.seed is not None else None)
return generator.permutation(self.indices)
self.sampler.set_epoch(epoch)
return self.indices[np.array(list(self.sampler))]
class XSequential(TraversalOrder):
def __init__(self, loader:'Loader'):
super().__init__(loader)
self.rank = int(os.environ["RANK"])
self.world_size = int(os.environ['WORLD_SIZE'])
if self.distributed:
self.sampler = DistributedSampler(self.indices,
num_replicas=self.world_size,
rank=self.rank,
shuffle=False,
seed=self.seed,
drop_last=False)
def sample_order(self, epoch: int) -> Sequence[int]:
if not self.distributed:
return self.indices
self.sampler.set_epoch(epoch)
return self.indices[np.array(list(self.sampler))]
class XPartition(TraversalOrder):
def __init__(self, loader:'Loader'):
super().__init__(loader)
self.rank = int(os.environ["RANK"])
self.world_size = int(os.environ['WORLD_SIZE'])
if self.distributed:
self.sampler = DistributedSampler(self.indices,
num_replicas=self.world_size,
rank=self.rank,
shuffle=True,
seed=self.seed,
drop_last=False)
def sample_order(self, epoch: int) -> Sequence[int]:
if not self.distributed:
raise ValueError('Partition order is only available in distributed mode')
# self.sampler.set_epoch(epoch)
if self.rank == 0:
print(f"sampled indices {self.indices[np.array(list(self.sampler))][:10]}")
return np.random.permutation(self.indices[np.array(list(self.sampler))])
def get_loader(
data_pth, batch_size, num_workers, drop_last, local_rank, train, seed, shuffle=1,
distributed=1, res=224, in_memory=1) -> Loader:
this_device = f'cuda:{local_rank}'
if train:
decoder = RandomResizedCropRGBImageDecoder((res, res))
image_pipeline: List[Operation] = [
decoder,
RandomHorizontalFlip(),
ToTensor(),
ToDevice(torch.device(this_device), non_blocking=True),
ToTorchImage(),
NormalizeImage(IMAGENET_MEAN, IMAGENET_STD, np.float16)
]
label_pipeline: List[Operation] = [
IntDecoder(),
ToTensor(),
Squeeze(),
ToDevice(torch.device(this_device), non_blocking=True)
]
# order = OrderOption.RANDOM
if shuffle:
order = XRandom
else:
if is_main_process():
print('Do not shuffle data among workers')
order = XPartition
loader = Loader(data_pth,
batch_size=batch_size,
num_workers=num_workers,
order=order,
os_cache=in_memory,
drop_last=drop_last,
pipelines={
'image': image_pipeline,
'label': label_pipeline
},
distributed=distributed,
seed=seed,
batches_ahead=3)
else:
cropper = CenterCropRGBImageDecoder((res, res), ratio=DEFAULT_CROP_RATIO)
image_pipeline = [
cropper,
ToTensor(),
ToDevice(torch.device(this_device), non_blocking=True),
ToTorchImage(),
NormalizeImage(IMAGENET_MEAN, IMAGENET_STD, np.float16)
]
label_pipeline = [
IntDecoder(),
ToTensor(),
Squeeze(),
ToDevice(torch.device(this_device),
non_blocking=True)
]
#OrderOption.SEQUENTIAL
loader = Loader(data_pth,
batch_size=batch_size,
num_workers=num_workers,
order=XSequential,
drop_last=False,
pipelines={
'image': image_pipeline,
'label': label_pipeline
},
distributed=distributed,
seed=seed,
batches_ahead=3)
return loader
def get_train_loader_strong_aug(
data_pth, batch_size, num_workers, drop_last, local_rank, seed, shuffle=1,
distributed=1, res=224, in_memory=1, depth=2, severity=10) -> Loader:
this_device = f'cuda:{local_rank}'
decoder = RandomResizedCropRGBImageDecoder((res, res))
image_pipeline: List[Operation] = [
decoder,
RandomHorizontalFlip(),
RandomAugment(severity=severity, depth=depth),
ToTensor(),
ToDevice(torch.device(this_device), non_blocking=True),
ToTorchImage(),
NormalizeImage(IMAGENET_MEAN, IMAGENET_STD, np.float16)
]
if is_main_process():
print(f'severity {severity}')
label_pipeline: List[Operation] = [
IntDecoder(),
ToTensor(),
Squeeze(),
ToDevice(torch.device(this_device), non_blocking=True)
]
if shuffle:
order = XRandom
else:
if is_main_process():
print('Do not shuffle data.')
order = XPartition
loader = Loader(data_pth,
batch_size=batch_size,
num_workers=num_workers,
order=order,
os_cache=in_memory,
drop_last=drop_last,
pipelines={
'image': image_pipeline,
'label': label_pipeline
},
distributed=distributed,
seed=seed,
batches_ahead=3)
return loader
if __name__ == "__main__":
# loader = get_loader(data_pth="/home/guxinran/ffcv_imagenet/train_500_0.50_90.ffcv", \
# batch_size=128, num_workers=12, drop_last=True, rank=0, train=1, \
# distributed=0, res=224, in_memory=1)
# print(len(loader))
print(issubclass(XRandom, TraversalOrder))