Datasets:

Modalities:
Image
Size:
< 1K
Libraries:
Datasets
License:
xianbao HF staff lyhue1991 commited on
Commit
47ccc0d
1 Parent(s): 9f8b4e2

Upload eat_accelerate_in_30_minites.md (#30)

Browse files

- Upload eat_accelerate_in_30_minites.md (a8b1663576de7dd28429cb45f9732d3d2be6c07f)


Co-authored-by: liangyun03 <lyhue1991@users.noreply.huggingface.co>

Files changed (1) hide show
  1. eat_accelerate_in_30_minites.md +595 -0
eat_accelerate_in_30_minites.md ADDED
@@ -0,0 +1,595 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # 30分钟吃掉accelerate模型训练加速工具
3
+
4
+
5
+ accelerate 是huggingface开源的一个方便将pytorch模型迁移到 GPU/multi-GPUs/TPU/fp16/bf16 模式下训练的小巧工具。
6
+
7
+ 和标准的 pytorch 方法相比,使用accelerate 进行多GPU DDP模式/TPU/fp16/bf16 训练你的模型变得非常简单,而且训练速度非常快。
8
+
9
+ 官方范例:https://github.com/huggingface/accelerate/tree/main/examples
10
+
11
+ 本文将以一个图片分类模型为例,演示在accelerate的帮助下使用pytorch编写一套可以在 cpu/单GPU/多GPU(DDP)模式/TPU 下通用的训练代码。
12
+
13
+ 在我们的演示范例中,在kaggle的双GPU环境下,双GPU(DDP)模式是单GPU训练速度的1.6倍,加速效果非常明显。
14
+
15
+
16
+
17
+
18
+ DP和DDP的区别
19
+
20
+ * DP(DataParallel):实现简单但更慢。只能单机多卡使用。GPU分成server节点和worker节点,有负载不均衡。
21
+
22
+ * DDP(DistributedDataParallel):更快但实现麻烦。可单机多卡也可多机多卡。各个GPU是平等的,无负载不均衡。
23
+
24
+ 参考文章:《pytorch中的分布式训练之DP VS DDP》https://zhuanlan.zhihu.com/p/356967195
25
+
26
+
27
+ ```python
28
+ #从git安装最新的accelerate仓库
29
+ !pip install git+https://github.com/huggingface/accelerate
30
+ ```
31
+
32
+
33
+
34
+ kaggle 源码:https://www.kaggle.com/code/lyhue1991/kaggle-ddp-tpu-examples
35
+
36
+
37
+
38
+ ## 一,使用 CPU/单GPU 训练你的pytorch模型
39
+
40
+
41
+ 当系统存在GPU时,accelerate 会自动使用GPU训练你的pytorch模型,否则会使用CPU训练模型。
42
+
43
+ ```python
44
+ import os,PIL
45
+ import numpy as np
46
+ from torch.utils.data import DataLoader, Dataset
47
+ import torch
48
+ from torch import nn
49
+
50
+ import torchvision
51
+ from torchvision import transforms
52
+ import datetime
53
+
54
+ #======================================================================
55
+ # import accelerate
56
+ from accelerate import Accelerator
57
+ from accelerate.utils import set_seed
58
+ #======================================================================
59
+
60
+
61
+ def create_dataloaders(batch_size=64):
62
+ transform = transforms.Compose([transforms.ToTensor()])
63
+
64
+ ds_train = torchvision.datasets.MNIST(root="./mnist/",train=True,download=True,transform=transform)
65
+ ds_val = torchvision.datasets.MNIST(root="./mnist/",train=False,download=True,transform=transform)
66
+
67
+ dl_train = torch.utils.data.DataLoader(ds_train, batch_size=batch_size, shuffle=True,
68
+ num_workers=2,drop_last=True)
69
+ dl_val = torch.utils.data.DataLoader(ds_val, batch_size=batch_size, shuffle=False,
70
+ num_workers=2,drop_last=True)
71
+ return dl_train,dl_val
72
+
73
+
74
+ def create_net():
75
+ net = nn.Sequential()
76
+ net.add_module("conv1",nn.Conv2d(in_channels=1,out_channels=512,kernel_size = 3))
77
+ net.add_module("pool1",nn.MaxPool2d(kernel_size = 2,stride = 2))
78
+ net.add_module("conv2",nn.Conv2d(in_channels=512,out_channels=256,kernel_size = 5))
79
+ net.add_module("pool2",nn.MaxPool2d(kernel_size = 2,stride = 2))
80
+ net.add_module("dropout",nn.Dropout2d(p = 0.1))
81
+ net.add_module("adaptive_pool",nn.AdaptiveMaxPool2d((1,1)))
82
+ net.add_module("flatten",nn.Flatten())
83
+ net.add_module("linear1",nn.Linear(256,128))
84
+ net.add_module("relu",nn.ReLU())
85
+ net.add_module("linear2",nn.Linear(128,10))
86
+ return net
87
+
88
+
89
+
90
+ def training_loop(epochs = 5,
91
+ lr = 1e-3,
92
+ batch_size= 1024,
93
+ ckpt_path = "checkpoint.pt",
94
+ mixed_precision="no", #'fp16' or 'bf16'
95
+ ):
96
+
97
+ train_dataloader, eval_dataloader = create_dataloaders(batch_size)
98
+ model = create_net()
99
+
100
+
101
+ optimizer = torch.optim.AdamW(params=model.parameters(), lr=lr)
102
+ lr_scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer=optimizer, max_lr=25*lr,
103
+ epochs=epochs, steps_per_epoch=len(train_dataloader))
104
+
105
+ #======================================================================
106
+ # initialize accelerator and auto move data/model to accelerator.device
107
+ set_seed(42)
108
+ accelerator = Accelerator(mixed_precision=mixed_precision)
109
+ accelerator.print(f'device {str(accelerator.device)} is used!')
110
+ model, optimizer,lr_scheduler, train_dataloader, eval_dataloader = accelerator.prepare(
111
+ model, optimizer,lr_scheduler, train_dataloader, eval_dataloader)
112
+ #======================================================================
113
+
114
+
115
+ for epoch in range(epochs):
116
+ model.train()
117
+ for step, batch in enumerate(train_dataloader):
118
+ features,labels = batch
119
+ preds = model(features)
120
+ loss = nn.CrossEntropyLoss()(preds,labels)
121
+
122
+ #======================================================================
123
+ #attention here!
124
+ accelerator.backward(loss) #loss.backward()
125
+ #======================================================================
126
+
127
+ optimizer.step()
128
+ lr_scheduler.step()
129
+ optimizer.zero_grad()
130
+
131
+
132
+ model.eval()
133
+ accurate = 0
134
+ num_elems = 0
135
+
136
+ for _, batch in enumerate(eval_dataloader):
137
+ features,labels = batch
138
+ with torch.no_grad():
139
+ preds = model(features)
140
+ predictions = preds.argmax(dim=-1)
141
+
142
+ #======================================================================
143
+ #gather data from multi-gpus (used when in ddp mode)
144
+ predictions = accelerator.gather_for_metrics(predictions)
145
+ labels = accelerator.gather_for_metrics(labels)
146
+ #======================================================================
147
+
148
+ accurate_preds = (predictions==labels)
149
+ num_elems += accurate_preds.shape[0]
150
+ accurate += accurate_preds.long().sum()
151
+
152
+ eval_metric = accurate.item() / num_elems
153
+
154
+ #======================================================================
155
+ #print logs and save ckpt
156
+ accelerator.wait_for_everyone()
157
+ nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
158
+ accelerator.print(f"epoch【{epoch}】@{nowtime} --> eval_metric= {100 * eval_metric:.2f}%")
159
+ net_dict = accelerator.get_state_dict(model)
160
+ accelerator.save(net_dict,ckpt_path+"_"+str(epoch))
161
+ #======================================================================
162
+
163
+ #training_loop(epochs = 5,lr = 1e-3,batch_size= 1024,ckpt_path = "checkpoint.pt",
164
+ # mixed_precision="no")
165
+
166
+ ```
167
+
168
+ ```python
169
+ training_loop(epochs = 5,lr = 1e-4,batch_size= 1024,
170
+ ckpt_path = "checkpoint.pt",
171
+ mixed_precision="no") #mixed_precision='fp16' or 'bf16'
172
+ ```
173
+
174
+ ```
175
+
176
+ device cuda is used!
177
+ epoch【0】@2023-01-15 12:06:45 --> eval_metric= 95.20%
178
+ epoch【1】@2023-01-15 12:07:01 --> eval_metric= 96.79%
179
+ epoch【2】@2023-01-15 12:07:17 --> eval_metric= 98.47%
180
+ epoch【3】@2023-01-15 12:07:34 --> eval_metric= 98.78%
181
+ epoch【4】@2023-01-15 12:07:51 --> eval_metric= 98.87%
182
+
183
+ ```
184
+
185
+
186
+
187
+ ## 二,使用多GPU DDP模式训练你的pytorch模型
188
+
189
+
190
+ Kaggle中右边settings 中的 ACCELERATOR选择 GPU T4x2。
191
+
192
+
193
+ ### 1,设置config
194
+
195
+ ```python
196
+ import os
197
+ from accelerate.utils import write_basic_config
198
+ write_basic_config() # Write a config file
199
+ os._exit(0) # Restart the notebook to reload info from the latest config file
200
+
201
+ ```
202
+
203
+ ```python
204
+ # or answer some question to create a config
205
+ #!accelerate config
206
+ ```
207
+
208
+ ```python
209
+ # %load /root/.cache/huggingface/accelerate/default_config.yaml
210
+ {
211
+ "compute_environment": "LOCAL_MACHINE",
212
+ "deepspeed_config": {},
213
+ "distributed_type": "MULTI_GPU",
214
+ "downcast_bf16": false,
215
+ "dynamo_backend": "NO",
216
+ "fsdp_config": {},
217
+ "machine_rank": 0,
218
+ "main_training_function": "main",
219
+ "megatron_lm_config": {},
220
+ "mixed_precision": "no",
221
+ "num_machines": 1,
222
+ "num_processes": 2,
223
+ "rdzv_backend": "static",
224
+ "same_network": false,
225
+ "use_cpu": false
226
+ }
227
+
228
+ ```
229
+
230
+ ### 2,训练代码
231
+
232
+
233
+ 与之前代码完全一致。
234
+
235
+ 如果是脚本方式启动,需要将训练代码写入到脚本文件中,如cv_example.py
236
+
237
+ ```python
238
+ %%writefile cv_example.py
239
+ import os,PIL
240
+ import numpy as np
241
+ from torch.utils.data import DataLoader, Dataset
242
+ import torch
243
+ from torch import nn
244
+
245
+ import torchvision
246
+ from torchvision import transforms
247
+ import datetime
248
+
249
+ #======================================================================
250
+ # import accelerate
251
+ from accelerate import Accelerator
252
+ from accelerate.utils import set_seed
253
+ #======================================================================
254
+
255
+
256
+ def create_dataloaders(batch_size=64):
257
+ transform = transforms.Compose([transforms.ToTensor()])
258
+
259
+ ds_train = torchvision.datasets.MNIST(root="./mnist/",train=True,download=True,transform=transform)
260
+ ds_val = torchvision.datasets.MNIST(root="./mnist/",train=False,download=True,transform=transform)
261
+
262
+ dl_train = torch.utils.data.DataLoader(ds_train, batch_size=batch_size, shuffle=True,
263
+ num_workers=2,drop_last=True)
264
+ dl_val = torch.utils.data.DataLoader(ds_val, batch_size=batch_size, shuffle=False,
265
+ num_workers=2,drop_last=True)
266
+ return dl_train,dl_val
267
+
268
+
269
+ def create_net():
270
+ net = nn.Sequential()
271
+ net.add_module("conv1",nn.Conv2d(in_channels=1,out_channels=512,kernel_size = 3))
272
+ net.add_module("pool1",nn.MaxPool2d(kernel_size = 2,stride = 2))
273
+ net.add_module("conv2",nn.Conv2d(in_channels=512,out_channels=256,kernel_size = 5))
274
+ net.add_module("pool2",nn.MaxPool2d(kernel_size = 2,stride = 2))
275
+ net.add_module("dropout",nn.Dropout2d(p = 0.1))
276
+ net.add_module("adaptive_pool",nn.AdaptiveMaxPool2d((1,1)))
277
+ net.add_module("flatten",nn.Flatten())
278
+ net.add_module("linear1",nn.Linear(256,128))
279
+ net.add_module("relu",nn.ReLU())
280
+ net.add_module("linear2",nn.Linear(128,10))
281
+ return net
282
+
283
+
284
+
285
+ def training_loop(epochs = 5,
286
+ lr = 1e-3,
287
+ batch_size= 1024,
288
+ ckpt_path = "checkpoint.pt",
289
+ mixed_precision="no", #'fp16' or 'bf16'
290
+ ):
291
+
292
+ train_dataloader, eval_dataloader = create_dataloaders(batch_size)
293
+ model = create_net()
294
+
295
+
296
+ optimizer = torch.optim.AdamW(params=model.parameters(), lr=lr)
297
+ lr_scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer=optimizer, max_lr=25*lr,
298
+ epochs=epochs, steps_per_epoch=len(train_dataloader))
299
+
300
+ #======================================================================
301
+ # initialize accelerator and auto move data/model to accelerator.device
302
+ set_seed(42)
303
+ accelerator = Accelerator(mixed_precision=mixed_precision)
304
+ accelerator.print(f'device {str(accelerator.device)} is used!')
305
+ model, optimizer,lr_scheduler, train_dataloader, eval_dataloader = accelerator.prepare(
306
+ model, optimizer,lr_scheduler, train_dataloader, eval_dataloader)
307
+ #======================================================================
308
+
309
+
310
+ for epoch in range(epochs):
311
+ model.train()
312
+ for step, batch in enumerate(train_dataloader):
313
+ features,labels = batch
314
+ preds = model(features)
315
+ loss = nn.CrossEntropyLoss()(preds,labels)
316
+
317
+ #======================================================================
318
+ #attention here!
319
+ accelerator.backward(loss) #loss.backward()
320
+ #======================================================================
321
+
322
+ optimizer.step()
323
+ lr_scheduler.step()
324
+ optimizer.zero_grad()
325
+
326
+
327
+ model.eval()
328
+ accurate = 0
329
+ num_elems = 0
330
+
331
+ for _, batch in enumerate(eval_dataloader):
332
+ features,labels = batch
333
+ with torch.no_grad():
334
+ preds = model(features)
335
+ predictions = preds.argmax(dim=-1)
336
+
337
+ #======================================================================
338
+ #gather data from multi-gpus (used when in ddp mode)
339
+ predictions = accelerator.gather_for_metrics(predictions)
340
+ labels = accelerator.gather_for_metrics(labels)
341
+ #======================================================================
342
+
343
+ accurate_preds = (predictions==labels)
344
+ num_elems += accurate_preds.shape[0]
345
+ accurate += accurate_preds.long().sum()
346
+
347
+ eval_metric = accurate.item() / num_elems
348
+
349
+ #======================================================================
350
+ #print logs and save ckpt
351
+ accelerator.wait_for_everyone()
352
+ nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
353
+ accelerator.print(f"epoch【{epoch}】@{nowtime} --> eval_metric= {100 * eval_metric:.2f}%")
354
+ net_dict = accelerator.get_state_dict(model)
355
+ accelerator.save(net_dict,ckpt_path+"_"+str(epoch))
356
+ #======================================================================
357
+
358
+ training_loop(epochs = 5,lr = 1e-4,batch_size= 1024,ckpt_path = "checkpoint.pt",
359
+ mixed_precision="no") #mixed_precision='fp16' or 'bf16'
360
+
361
+ ```
362
+
363
+ ### 3,执行代码
364
+
365
+
366
+ **方式1,在notebook中启动**
367
+
368
+ ```python
369
+ from accelerate import notebook_launcher
370
+ #args = (5,1e-4,1024,'checkpoint.pt','no')
371
+ args = dict(epochs = 5,
372
+ lr = 1e-4,
373
+ batch_size= 1024,
374
+ ckpt_path = "checkpoint.pt",
375
+ mixed_precision="no").values()
376
+ notebook_launcher(training_loop, args, num_processes=2)
377
+
378
+
379
+ ```
380
+
381
+ ```
382
+ Launching training on 2 GPUs.
383
+ device cuda:0 is used!
384
+ epoch【0】@2023-01-15 12:10:48 --> eval_metric= 89.18%
385
+ epoch【1】@2023-01-15 12:10:58 --> eval_metric= 97.20%
386
+ epoch【2】@2023-01-15 12:11:08 --> eval_metric= 98.03%
387
+ epoch【3】@2023-01-15 12:11:19 --> eval_metric= 98.16%
388
+ epoch【4】@2023-01-15 12:11:30 --> eval_metric= 98.32%
389
+ ```
390
+
391
+
392
+
393
+ **方式2,accelerate方式执行脚本**
394
+
395
+ ```python
396
+ !accelerate launch ./cv_example.py
397
+ ```
398
+
399
+ ```
400
+ device cuda:0 is used!
401
+ epoch【0】@2023-02-03 11:38:02 --> eval_metric= 91.79%
402
+ epoch【1】@2023-02-03 11:38:13 --> eval_metric= 97.22%
403
+ epoch【2】@2023-02-03 11:38:22 --> eval_metric= 98.18%
404
+ epoch【3】@2023-02-03 11:38:32 --> eval_metric= 98.33%
405
+ epoch【4】@2023-02-03 11:38:43 --> eval_metric= 98.38%
406
+ ```
407
+
408
+
409
+ **方式3,torch方式执行脚本**
410
+
411
+ ```python
412
+ # or traditional pytorch style
413
+ !python -m torch.distributed.launch --nproc_per_node 2 --use_env ./cv_example.py
414
+ ```
415
+
416
+ ```
417
+ device cuda:0 is used!
418
+ epoch【0】@2023-01-15 12:18:26 --> eval_metric= 94.79%
419
+ epoch【1】@2023-01-15 12:18:37 --> eval_metric= 96.44%
420
+ epoch【2】@2023-01-15 12:18:48 --> eval_metric= 98.34%
421
+ epoch【3】@2023-01-15 12:18:59 --> eval_metric= 98.41%
422
+ epoch【4】@2023-01-15 12:19:10 --> eval_metric= 98.51%
423
+ ```
424
+
425
+
426
+
427
+ ## 三,使用TPU加速你的pytorch模型
428
+
429
+
430
+ Kaggle中右边settings 中的 ACCELERATOR选择 TPU v3-8。
431
+
432
+
433
+ ### 1,安装torch_xla
434
+
435
+ ```python
436
+ #安装torch_xla支持
437
+ !pip uninstall -y torch torch_xla
438
+ !pip install torch==1.8.2+cpu -f https://download.pytorch.org/whl/lts/1.8/torch_lts.html
439
+ !pip install cloud-tpu-client==0.10 https://storage.googleapis.com/tpu-pytorch/wheels/torch_xla-1.8-cp37-cp37m-linux_x86_64.whl
440
+ ```
441
+
442
+ ```python
443
+ #从git安装最新的accelerate仓库
444
+ !pip install git+https://github.com/huggingface/accelerate
445
+ ```
446
+
447
+ ```python
448
+ #检查是否成功安装 torch_xla
449
+ import torch_xla
450
+ ```
451
+
452
+ ### 2,训练代码
453
+
454
+
455
+ 和之前代码完全一样。
456
+
457
+ ```python
458
+ import os,PIL
459
+ import numpy as np
460
+ from torch.utils.data import DataLoader, Dataset
461
+ import torch
462
+ from torch import nn
463
+
464
+ import torchvision
465
+ from torchvision import transforms
466
+ import datetime
467
+
468
+ #======================================================================
469
+ # import accelerate
470
+ from accelerate import Accelerator
471
+ from accelerate.utils import set_seed
472
+ #======================================================================
473
+
474
+
475
+ def create_dataloaders(batch_size=64):
476
+ transform = transforms.Compose([transforms.ToTensor()])
477
+
478
+ ds_train = torchvision.datasets.MNIST(root="./mnist/",train=True,download=True,transform=transform)
479
+ ds_val = torchvision.datasets.MNIST(root="./mnist/",train=False,download=True,transform=transform)
480
+
481
+ dl_train = torch.utils.data.DataLoader(ds_train, batch_size=batch_size, shuffle=True,
482
+ num_workers=2,drop_last=True)
483
+ dl_val = torch.utils.data.DataLoader(ds_val, batch_size=batch_size, shuffle=False,
484
+ num_workers=2,drop_last=True)
485
+ return dl_train,dl_val
486
+
487
+
488
+ def create_net():
489
+ net = nn.Sequential()
490
+ net.add_module("conv1",nn.Conv2d(in_channels=1,out_channels=512,kernel_size = 3))
491
+ net.add_module("pool1",nn.MaxPool2d(kernel_size = 2,stride = 2))
492
+ net.add_module("conv2",nn.Conv2d(in_channels=512,out_channels=256,kernel_size = 5))
493
+ net.add_module("pool2",nn.MaxPool2d(kernel_size = 2,stride = 2))
494
+ net.add_module("dropout",nn.Dropout2d(p = 0.1))
495
+ net.add_module("adaptive_pool",nn.AdaptiveMaxPool2d((1,1)))
496
+ net.add_module("flatten",nn.Flatten())
497
+ net.add_module("linear1",nn.Linear(256,128))
498
+ net.add_module("relu",nn.ReLU())
499
+ net.add_module("linear2",nn.Linear(128,10))
500
+ return net
501
+
502
+
503
+
504
+ def training_loop(epochs = 5,
505
+ lr = 1e-3,
506
+ batch_size= 1024,
507
+ ckpt_path = "checkpoint.pt",
508
+ mixed_precision="no", #fp16' or 'bf16'
509
+ ):
510
+
511
+ train_dataloader, eval_dataloader = create_dataloaders(batch_size)
512
+ model = create_net()
513
+
514
+
515
+ optimizer = torch.optim.AdamW(params=model.parameters(), lr=lr)
516
+ lr_scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer=optimizer, max_lr=25*lr,
517
+ epochs=epochs, steps_per_epoch=len(train_dataloader))
518
+
519
+ #======================================================================
520
+ # initialize accelerator and auto move data/model to accelerator.device
521
+ set_seed(42)
522
+ accelerator = Accelerator(mixed_precision=mixed_precision)
523
+ accelerator.print(f'device {str(accelerator.device)} is used!')
524
+ model, optimizer,lr_scheduler, train_dataloader, eval_dataloader = accelerator.prepare(
525
+ model, optimizer,lr_scheduler, train_dataloader, eval_dataloader)
526
+ #======================================================================
527
+
528
+
529
+ for epoch in range(epochs):
530
+ model.train()
531
+ for step, batch in enumerate(train_dataloader):
532
+ features,labels = batch
533
+ preds = model(features)
534
+ loss = nn.CrossEntropyLoss()(preds,labels)
535
+
536
+ #======================================================================
537
+ #attention here!
538
+ accelerator.backward(loss) #loss.backward()
539
+ #======================================================================
540
+
541
+ optimizer.step()
542
+ lr_scheduler.step()
543
+ optimizer.zero_grad()
544
+
545
+
546
+ model.eval()
547
+ accurate = 0
548
+ num_elems = 0
549
+
550
+ for _, batch in enumerate(eval_dataloader):
551
+ features,labels = batch
552
+ with torch.no_grad():
553
+ preds = model(features)
554
+ predictions = preds.argmax(dim=-1)
555
+
556
+ #======================================================================
557
+ #gather data from multi-gpus (used when in ddp mode)
558
+ predictions = accelerator.gather_for_metrics(predictions)
559
+ labels = accelerator.gather_for_metrics(labels)
560
+ #======================================================================
561
+
562
+ accurate_preds = (predictions==labels)
563
+ num_elems += accurate_preds.shape[0]
564
+ accurate += accurate_preds.long().sum()
565
+
566
+ eval_metric = accurate.item() / num_elems
567
+
568
+ #======================================================================
569
+ #print logs and save ckpt
570
+ accelerator.wait_for_everyone()
571
+ nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
572
+ accelerator.print(f"epoch【{epoch}】@{nowtime} --> eval_metric= {100 * eval_metric:.2f}%")
573
+ net_dict = accelerator.get_state_dict(model)
574
+ accelerator.save(net_dict,ckpt_path+"_"+str(epoch))
575
+ #======================================================================
576
+
577
+ #training_loop(epochs = 5,lr = 1e-3,batch_size= 1024,ckpt_path = "checkpoint.pt",
578
+ # mixed_precision="no") #mixed_precision='fp16' or 'bf16'
579
+
580
+ ```
581
+
582
+ ### 3,启动训练
583
+
584
+ ```python
585
+ from accelerate import notebook_launcher
586
+ #args = (5,1e-4,1024,'checkpoint.pt','no')
587
+ args = dict(epochs = 5,
588
+ lr = 1e-4,
589
+ batch_size= 1024,
590
+ ckpt_path = "checkpoint.pt",
591
+ mixed_precision="no").values()
592
+ notebook_launcher(training_loop, args, num_processes=8)
593
+
594
+ ```
595
+