-
Notifications
You must be signed in to change notification settings - Fork 3
/
benchmark.py
364 lines (351 loc) · 15.3 KB
/
benchmark.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
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
# Benchmark models
import torch
from torch import nn
import torch.optim as optim
from time import time
import logging
from fvcore.nn import FlopCountAnalysis ## thank you Meta
def benchmark_dataloader(dataloader, itr:int =100, device='cpu', dtype=torch.float32, mixup=None, verbose=True):
"""
Run benchmark for `itr' iterations on dataloader
Args:
dataloader: pytorch dataloader object
itr: iteration limit
device: device (cpu, cuda, or cuda index)
dtype: dtype (default: torch.float32)
verbose: Print result
Returns:
time_took: time took in seconds
img_count: number of processed images
"""
inittime=time()
idx = 0 # tracks current index
img_count = 0
init_took = 0
time_took = 0
while idx < itr:
for i, data in enumerate(dataloader):
if i == 0:
starttime = time()
if idx >= itr:
break
inputs, labels = data
labels = labels.to(device)
img_count += data[1].shape[0]
if type(inputs) == list or type(inputs) == set:
# DCT
y = inputs[0]
cbcr = inputs[1]
y = y.to(device)
cbcr = cbcr.to(device)
else:
# RGB
inputs = inputs.to(device) # send to gpu
if verbose:
print(f"\rBenchmarking dataloader... {idx+1}/{itr}", end="", flush=True)
idx += 1
endtime = time()
time_took += endtime - starttime
init_took += starttime - inittime
inittime = time()
if verbose:
print("\n", end="")
logging.info(f" Dataloader took: {time_took:.2f} sec for {idx} itrs / {img_count} imgs. {img_count/time_took:.2f} FPS. Init took {init_took:.2f} sec")
return time_took, img_count
def benchmark_modelfbp_rgb(model, Imgshape=(128, 3, 224, 224), outshape=(128, ),
itr:int =100, mode='fbp', criterion=nn.CrossEntropyLoss(), use_amp=False, mixup=None,
device='cpu', dtype=torch.float32, verbose=True):
"""
Run benchmark for `itr' iterations on model forward/backward pass (dct)
Args:
model: pytorch model
Imgshape (tuple): model input shape (including batch dimension)
itr: iteration limit
criterion: dummy criterion to use (default: nn.CrossEntropyLoss)
use_amp: use automatic mixed precision
device: device (cpu, cuda, or cuda index)
dtype: dtype (default: torch.float32)
verbose: print result if true
Return:
time_took: time took in seconds
img_count: number of processed images
"""
dummy_data = torch.randn(Imgshape, device="cpu", dtype=dtype)
dummy_out = torch.randint(0, 999, outshape, device="cpu", dtype=torch.int64)
dummy_data = dummy_data.to(device)
dummy_out = dummy_out.to(device)
optimizer = optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0, eps=1e-4)
img_count = 0
if mode=="fwd":
dummy_data_clone = dummy_data.clone()
dummy_out_clone = dummy_out.clone()
inittime=time()
if use_amp:
gradscaler = torch.cuda.amp.GradScaler()
with torch.set_grad_enabled(mode=='fbp'):
for i in range(itr):
if i == 0:
starttime = time()
if mode=='fbp':
optimizer.zero_grad()
dummy_data_clone = dummy_data.clone()
dummy_out_clone = dummy_out.clone()
with torch.cuda.amp.autocast(enabled=use_amp, dtype=torch.float16):
if mode=="fbp" and mixup:
dummy_data_clone, dummy_out_clone = mixup(dummy_data_clone, dummy_out_clone)
output = model(dummy_data_clone)
loss = criterion(output, dummy_out_clone)
if mode=='fbp':
if use_amp:
gradscaler.scale(loss).backward()
gradscaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1)
gradscaler.step(optimizer)
gradscaler.update()
else:
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1)
optimizer.step()
img_count += outshape[0]
if verbose:
print(f"\rBenchmarking model F/B pass... {i+1}/{itr}", end="", flush=True)
endtime=time()
init_took = starttime-inittime
time_took = endtime-starttime
if verbose:
print("\n", end="")
logging.info(f" Model F/B pass (mode:{mode}, amp:{use_amp}) took: took: {time_took:.2f} sec for {itr} itrs / {img_count} imgs. {img_count / time_took:.2f} FPS. Init took {init_took:.2f} sec")
return time_took, img_count
def benchmark_modelfbp_dct(model, Yshape=(128, 28, 28, 1, 8, 8), Cshape=(128, 14, 14, 2, 8, 8), outshape=(128, ),
itr:int =100, mode='fbp', criterion=nn.CrossEntropyLoss(), use_amp=False, mixup=None,
device='cpu', dtype=torch.float32, verbose=True):
"""
Run benchmark for `itr' iterations on model forward/backward pass (dct)
Args:
model: pytorch model
Yshape (tuple): model input shape (Y)(including batch dimension)
Cshape (tuple): model input shape (CbCr)
itr: iteration limit
mode: 'fbp' or 'fwd'
criterion: dummy criterion to use (default: nn.CrossEntropyLoss)
use_amp: use amp if true
device: device (cpu, cuda, or cuda index)
dtype: dtype (default: torch.float32)
verbose: print result if true
Return:
time_took: time took in seconds
img_count: number of processed images
"""
dummy_data_Y = torch.randn(Yshape, device="cpu", dtype=dtype)
dummy_data_C = torch.randn(Cshape, device="cpu", dtype=dtype)
dummy_out = torch.randint(0, 999, outshape, device="cpu", dtype=torch.int64)
dummy_data_Y = dummy_data_Y.to(device)
dummy_data_C = dummy_data_C.to(device)
dummy_out = dummy_out.to(device)
assert dummy_out.ndim == 1, f"Dummy out should have one dimension. Current: {dummy_out.shape}, {dummy_out.ndim}"
optimizer = optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0, eps=1e-4)
img_count=0
if mode=="fwd":
dummy_data_Y_clone = dummy_data_Y.clone()
dummy_data_C_clone = dummy_data_C.clone()
dummy_out_clone = dummy_out.clone()
inittime=time()
if use_amp:
gradscaler = torch.cuda.amp.GradScaler()
with torch.set_grad_enabled(mode=='fbp'):
for i in range(itr):
if i == 0:
starttime = time()
if mode=='fbp':
optimizer.zero_grad()
dummy_data_Y_clone = dummy_data_Y.clone()
dummy_data_C_clone = dummy_data_C.clone()
dummy_out_clone = dummy_out.clone()
with torch.cuda.amp.autocast(enabled=use_amp, dtype=torch.float16):
if mode=="fbp" and mixup:
(dummy_data_Y_clone, dummy_data_C_clone), dummy_out_clone = \
mixup((dummy_data_Y_clone, dummy_data_C_clone), dummy_out_clone)
output = model(dummy_data_Y_clone, dummy_data_C_clone)
loss = criterion(output, dummy_out_clone)
if mode=='fbp':
if use_amp:
gradscaler.scale(loss).backward()
gradscaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1)
gradscaler.step(optimizer)
gradscaler.update()
else:
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1)
optimizer.step()
img_count += outshape[0]
if verbose:
print(f"\rBenchmarking model F/B pass... {i+1}/{itr}", end="", flush=True)
endtime=time()
init_took = starttime-inittime
time_took = endtime-starttime
if verbose:
print("\n", end="")
logging.info(f" Model F/B pass (mode:{mode}, amp:{use_amp}) took: {time_took:.2f} sec for {itr} itrs / {img_count} imgs. {img_count / time_took:.2f} FPS. Init took {init_took:.2f} sec")
return time_took, img_count
def benchmark_mixup_rgb(Imgshape=(128, 3, 224, 224), outshape=(128, ),
itr:int =100, mixup=None,
device='cpu', dtype=torch.float32, verbose=True):
"""
Run benchmark for `itr' iterations on model forward/backward pass (dct)
Args:
model: pytorch model
Imgshape (tuple): model input shape (including batch dimension)
itr: iteration limit
criterion: dummy criterion to use (default: nn.CrossEntropyLoss)
use_amp: use automatic mixed precision
device: device (cpu, cuda, or cuda index)
dtype: dtype (default: torch.float32)
verbose: print result if true
Return:
time_took: time took in seconds
img_count: number of processed images
"""
dummy_data = torch.randn(Imgshape, device="cpu", dtype=dtype)
dummy_out = torch.randint(0, 999, outshape, device="cpu", dtype=torch.int64)
img_count = 0
time_took = 0
init_took = 0
inittime=time()
starttime = time()
if mixup==None:
return 1,1
for i in range(itr):
dummy_data_clone = dummy_data.clone()
dummy_out_clone = dummy_out.clone()
dummy_data_clone = dummy_data_clone.to(device)
dummy_out_clone = dummy_out_clone.to(device)
img_count += outshape[0]
if verbose:
print(f"\rBenchmarking memory copy ... {i+1}/{itr}", end="", flush=True)
endtime=time()
time_took += endtime-starttime
init_took = starttime-inittime
if verbose:
print("\n", end="")
logging.info(f" Mem Transfer (RGB) took: took: {time_took:.3f} sec for {itr*10} itrs / {img_count} imgs. {time_took/img_count*1000:.3f} ms/img. Init took {init_took:.2f} sec")
return time_took, img_count
def benchmark_mixup_dct(Yshape=(128, 28, 28, 1, 8, 8), Cshape=(128, 14, 14, 2, 8, 8), outshape=(128, ),
itr:int =100, mixup=None,
device='cpu', dtype=torch.float32, verbose=True):
"""
Run benchmark for `itr' iterations on model forward/backward pass (dct)
Args:
model: pytorch model
Imgshape (tuple): model input shape (including batch dimension)
itr: iteration limit
criterion: dummy criterion to use (default: nn.CrossEntropyLoss)
use_amp: use automatic mixed precision
device: device (cpu, cuda, or cuda index)
dtype: dtype (default: torch.float32)
verbose: print result if true
Return:
time_took: time took in seconds
img_count: number of processed images
"""
dummy_data_Y = torch.randn(Yshape, device="cpu", dtype=dtype)
dummy_data_C = torch.randn(Cshape, device="cpu", dtype=dtype)
dummy_out = torch.randint(0, 999, outshape, device="cpu", dtype=torch.int64)
img_count = 0
time_took=0
init_took=0
inittime=time()
starttime = time()
if mixup == None:
return 1, 1
for i in range(itr):
dummy_data_Y_clone = dummy_data_Y.clone()
dummy_data_C_clone = dummy_data_C.clone()
dummy_out_clone = dummy_out.clone()
dummy_data_Y_clone = dummy_data_Y_clone.to(device)
dummy_data_C_clone = dummy_data_C_clone.to(device)
dummy_out_clone = dummy_out_clone.to(device)
img_count += outshape[0]
if verbose:
print(f"\rBenchmarking mixup ... {i+1}/{itr}", end="", flush=True)
endtime=time()
time_took = endtime-starttime
init_took = starttime-inittime
if verbose:
print("\n", end="")
logging.info(f" Mem Transfer (DCT) took: took: {time_took:.3f} sec for {itr*10} itrs / {img_count} imgs. {time_took/img_count*1000:.3f} ms/img. Init took {init_took:.2f} sec")
return time_took, img_count
def benchmark_pipeline(model, dataloader, itr, criterion=nn.CrossEntropyLoss(), use_amp=False, mixup=None,
mode='train', modeltype='dct', device='cpu', dtype=torch.float32, verbose=True):
"""
Run benchmark of a trainig pipeline .
Args:
model: pytorch model
dataloader: dataloader
itr: iteration limit
criterion: dummy criterion to use (default: nn.CrossEntropyLoss)
mode: 'train' or 'test' -- 'test' doesn't do backprop
modeltype: Model type (DCT or RGB)
device: device (cpu, cuda, or cuda index)
dtype: dtype (default: torch.float32)
verbose: print result if true
Return:
time_took: time took in seconds
"""
optimizer = optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0, eps=1e-4)
inittime=time()
idx = 0 # tracks current index
init_took=0
time_took=0
img_count=0
if use_amp:
gradscaler = torch.cuda.amp.GradScaler()
with torch.set_grad_enabled(mode=='train'):
while idx < itr:
for i, data in enumerate(dataloader):
if i == 0:
starttime = time()
if idx >= itr:
break
inputs, labels = data
labels = labels.to(device)
if mode=='train':
optimizer.zero_grad()
with torch.cuda.amp.autocast(enabled=use_amp, dtype=torch.float16):
if modeltype=='dct':
y = inputs[0]
cbcr = inputs[1]
y = y.to(device)
cbcr = cbcr.to(device)
if mode=="train" and mixup:
(y, cbcr), labels = mixup((y, cbcr), labels)
output = model(y, cbcr)
else:
inputs = inputs.to(device)
if mode=="train" and mixup:
inputs, labels = mixup(inputs, labels)
output = model(inputs)
loss = criterion(output, labels)
if mode=='train':
if use_amp:
gradscaler.scale(loss).backward()
gradscaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1)
gradscaler.step(optimizer)
gradscaler.update()
else:
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1)
optimizer.step()
img_count += labels.shape[0]
if verbose:
print(f"\rBenchmarking pipeline... {idx+1}/{itr}", end="", flush=True)
idx += 1
endtime = time()
time_took += endtime - starttime
init_took += starttime - inittime
inittime = time()
if verbose:
print("\n", end="")
logging.info(f" Pipeline (amp: {use_amp}) took: {time_took:.2f} sec for {idx} itrs / {img_count} imgs. {img_count / time_took:.2f} FPS. Init took {init_took:.2f} sec")
return time_took, img_count