Newer
Older
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "EBL97zOSNOUb"
},
"source": [
"<img width=\"800px\" src=\"../fidle/img/header.svg\"></img>\n",
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"\n",
"# <!-- TITLE --> [OPT1] - Training setup optimization\n",
"<!-- DESC --> The goal of this notebook is to go through a typical deep learning model training\n",
"\n",
"<!-- AUTHOR : Kamel Guerda (CNRS/IDRIS), Léo Hunout (CNRS/IDRIS) -->\n",
"\n",
"## Objectives :\n",
"\n",
"\n",
"**Practice lab : Optimize your training process**"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "wmsmK2lGelCE"
},
"source": [
"## Introduction\n",
"\n",
"This Lab takes place as a pratical exercice of the [fidle](https://fidle.cnrs.fr/) online course N°16.\n",
"\n",
"\n",
"The goal of this notebook is to go through a typical deep learning model training. We will see what can be changed to optimize this training setup but also good practices to make more efficient experiments.\n",
"\n",
"\n",
"This notebook makes use of:\n",
"- The CIFAR10 dataset\n",
"- A Resnet model\n",
"- Pytorch\n",
"- A GPU (the notebook can be ran on Jean-Zay if you have an account, on Google collab with a 16go gpu or at home with a dedicated gpu by scaling down the batch_size)\n",
"\n",
"In particular we will work on:\n",
"- the dataloader strategy used to load data\n",
"- the model initial weights, in particular using a pretrained model\n",
"- the learning rate and learning rate scheduler\n",
"- the optimizer\n",
"- visualizing and comparing results using python, tensorboard\n",
"- various good practices/reminders\n",
"\n",
"> First, you can do a complete execution of the notebook.\n",
"\n",
"> **Then comeback from the start and follow the instructions to edit various components for better performance. You can also change them during the first execution if you have some intuitions about what should be changed and how.**\n",
"\n",
"> **In order to compare performance, only change the xxx_optim variables which are the one you will use in your optimized training**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "UrJW8d_lqZ-l"
},
"outputs": [],
"source": [
"!nvidia-smi"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "527LDYwLf9gB"
},
"source": [
"## Few imports"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "mPEZLMywejMG"
},
"outputs": [],
"source": [
"import os\n",
"import time\n",
"import random\n",
"import numpy as np\n",
"\n",
"import torch\n",
"from torch.cuda.amp import autocast, GradScaler\n",
"from torch.optim.lr_scheduler import _LRScheduler\n",
"\n",
"import torchvision\n",
"import torchvision.transforms as transforms\n",
"import torchvision.models as models\n",
"from torchvision.models.resnet import ResNet18_Weights\n",
"\n",
"import matplotlib.pyplot as plt\n",
"\n",
"from datetime import datetime\n",
"from torch.utils.tensorboard import SummaryWriter"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "G_DozO12fv8o"
},
"source": [
"## Fix random seeds\n",
"In order to have experiment reproductibility, it is a good practice to fix the random number generators seeds.\n",
"\n",
"Warning : there might be more seeds to set than you expect! Maths,visualization,transformations libraries, ..."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Y9jOl-D8ejWw"
},
"outputs": [],
"source": [
"random.seed(123)\n",
"np.random.seed(123)\n",
"torch.manual_seed(123)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9nZlyar5NOUr"
},
"source": [
"## Some functions\n",
"\n",
"Below we define a few functions that will be used further in the notebook. \n",
"\n",
"**Do not change them unless you know what and why you are doing it.**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "JFQtFuDWNOUt"
},
"outputs": [],
"source": [
"def iter_dataloader(dataloader, epochs, args):\n",
" for epoch in range(epochs):\n",
" for i, (images, labels) in enumerate(dataloader):\n",
" # distribution of images and labels to all GPUs\n",
" images = images.to(args['device'], non_blocking=True)\n",
" labels = labels.to(args['device'], non_blocking=True)\n",
" \n",
"def evaluate(dataloader, model, criterion, args):\n",
" '''\n",
" A simple loop for evaluation\n",
" '''\n",
" loss = 0\n",
" correct = 0\n",
" total = 0\n",
" with torch.no_grad():\n",
" for i, (images, labels) in enumerate(dataloader):\n",
" # distribution of images and labels to all GPUs\n",
" images = images.to(args['device'], non_blocking=True)\n",
" labels = labels.to(args['device'], non_blocking=True)\n",
" outputs = model(images)\n",
" loss = criterion(outputs,labels)\n",
" _, predicted = torch.max(outputs.data, 1)\n",
"\n",
" loss += loss\n",
" total += labels.size(0)\n",
" correct += (predicted == labels).sum().item()\n",
" loss = (loss/total).item()\n",
" accuracy = (correct/total)*100\n",
" return loss, accuracy\n",
"\n",
"def train_default(train_loader, val_loader, model, optimizer, criterion, args):\n",
" '''\n",
" The default simple training loop\n",
" '''\n",
" train_losses = []\n",
" train_accuracies = []\n",
" val_losses = []\n",
" val_accuracies = []\n",
" time_start = time.time()\n",
" for epoch in range(args['epochs']):\n",
" print(\"Epoch \", epoch)\n",
" for i, (images, labels) in enumerate(train_loader):\n",
" # distribution of images and labels to all GPUs\n",
" images = images.to(args['device'], non_blocking=True)\n",
" labels = labels.to(args['device'], non_blocking=True)\n",
" \n",
" # Zero the parameter gradients\n",
" optimizer.zero_grad()\n",
"\n",
" # Forward pass\n",
" outputs = model(images)\n",
" loss = criterion(outputs, labels)\n",
"\n",
" # Backward pass\n",
" loss.backward()\n",
"\n",
" # Optimize\n",
" optimizer.step()\n",
"\n",
" # Evaluate at the end of the epoch on the train set\n",
" train_loss, train_accuracy = evaluate(train_loader, model, criterion, args)\n",
" print(\"\\t Train loss : \", train_loss, \"& Train accuracy : \", train_accuracy)\n",
" train_losses.append(train_loss)\n",
" train_accuracies.append(train_accuracy) \n",
" \n",
" # Evaluate at the end of the epoch on the val set\n",
" val_loss, val_accuracy = evaluate(val_loader, model, criterion, args)\n",
" print(\"\\t Validation loss : \", val_loss, \"& Validation accuracy : \", val_accuracy)\n",
" val_losses.append(val_loss)\n",
" val_accuracies.append(val_accuracy)\n",
" \n",
" duration = time.time() - time_start\n",
" print('Finished Training in:', duration, 'seconds with mean epoch duration:', duration/args['epochs'], ' seconds')\n",
" results = {'model':model,\n",
" 'train_losses': train_losses,\n",
" 'train_accuracies': train_accuracies,\n",
" 'val_losses': val_losses,\n",
" 'val_accuracies': val_accuracies,\n",
" 'duration':duration}\n",
" return results\n",
"\n",
"def explore_lrs(dataloader, \n",
" model, \n",
" optimizer,\n",
" args,\n",
" min_learning_rate_power=-8, \n",
" max_learning_rate_power = 1,\n",
" num_lrs=10,\n",
" steps_per_lr=50):\n",
" \n",
" lrs = np.logspace(min_learning_rate_power, max_learning_rate_power, num=num_lrs)\n",
" print(\"Learning rate space : \", lrs)\n",
" model_init_state = model.state_dict()\n",
"\n",
" lrs_losses, lrs_metric_avg, lrs_metric_var =[], [],[]\n",
" \n",
" # Iterate through learning rates to test\n",
" for lr in lrs:\n",
" print(\"Testing lr:\", '{:.2e}'.format(lr))\n",
" # Reset model\n",
" model.load_state_dict(model_init_state)\n",
"\n",
" # Change learning rate in optimizer\n",
" for group in optimizer.param_groups:\n",
" group['lr'] = lr\n",
"\n",
" # Reset metric tracking\n",
" lr_losses =[]\n",
"\n",
" # Training steps\n",
" for step in range(steps_per_lr):\n",
" images, labels = next(iter(dataloader))\n",
" # distribution of images and labels to all GPUs\n",
" images = images.to(args['device'], non_blocking=True)\n",
" labels = labels.to(args['device'], non_blocking=True)\n",
" optimizer.zero_grad()\n",
" outputs = model(images)\n",
" loss = criterion(outputs, labels)\n",
" loss.backward()\n",
" optimizer.step()\n",
" lr_losses.append(loss.item())\n",
" print(lr_losses)\n",
"\n",
" # Compute loss average for lr\n",
" lr_loss_avg = np.mean(lr_losses) \n",
" lr_loss_avg = lr_losses[-1]\n",
"\n",
" lrs_losses.append(lr_loss_avg)\n",
"\n",
" # Compute metric (discounted average gradient of the loss)\n",
" lr_gradients = np.gradient(lr_losses)\n",
" lr_metric_avg = np.mean(lr_gradients)\n",
" lr_metric_var = np.var(lr_gradients)\n",
" lrs_metric_avg.append(lr_metric_avg) \n",
" lrs_metric_var.append(lr_metric_var)\n",
" model.load_state_dict(model_init_state)\n",
"\n",
" return lrs, lrs_losses, lrs_metric_avg, lrs_metric_var\n",
"\n",
"def plot_eval(lrs, lrs_losses, lrs_metric_avg, lrs_metric_var):\n",
" print(\"lrs: \", lrs)\n",
" print(\"lrs_losses: \", lrs_losses)\n",
" print(\"lrs_metric_avg: \", lrs_metric_avg)\n",
" print(\"lrs_metric_var: \", lrs_metric_var)\n",
" fig, axs = plt.subplots(3, figsize=(10,15))\n",
"\n",
" axs[0].plot(lrs, lrs_losses, color='blue', label=\"losses_avg\")\n",
" axs[0].set_xlabel('learning rate', fontsize=15)\n",
" axs[0].set_ylabel('Loss', fontsize=15)\n",
" axs[0].set_xscale('log')\n",
" axs[0].set_yscale('symlog')\n",
" axs[0].set_ylim([0, min(lrs_losses)*100])\n",
"\n",
" axs[1].plot(lrs, lrs_metric_avg, color='red', label=\"discounted_metric_avg\")\n",
" axs[1].hlines(y=0, xmin=lrs[0], xmax=lrs[-1], linewidth=2, color='black')\n",
" axs[1].set_xlabel('learning rate', fontsize=15)\n",
" axs[1].set_ylabel('Metric average', fontsize=15)\n",
" axs[1].set_xscale('log')\n",
" axs[1].set_yscale('symlog')\n",
" axs[1].set_ylim([-abs(lrs_metric_avg[0])*100, abs(lrs_metric_avg[0])*100])\n",
"\n",
" axs[2].plot(lrs, lrs_metric_var, color='green', label=\"discounted_metric_var\")\n",
" axs[2].set_xlabel('learning rate', fontsize=15)\n",
" axs[2].set_ylabel('Metric variance', fontsize=15)\n",
" axs[2].set_xscale('log')\n",
" axs[2].set_yscale('symlog')\n",
" axs[2].set_ylim([0, min(lrs_metric_var)*1000])\n",
"\n",
" plt.show()\n",
" \n",
"def compare_trainings(results_default, results_optim):\n",
" fig, axs = plt.subplots(2, figsize=(10,10))\n",
" fig.suptitle('Performance comparison', fontsize=18) \n",
" \n",
" train_alpha = 0.5\n",
" \n",
" # Validation losses \n",
" axs[0].plot(range(len(results_default['val_losses'])), results_default['val_losses'], color='blue', label=\"default val\")\n",
" axs[0].plot(range(len(results_optim['val_losses'])), results_optim['val_losses'], color='red', label=\"optim val\")\n",
"\n",
" # Training losses \n",
" axs[0].plot(range(len(results_default['train_losses'])), results_default['train_losses'], color='blue', label=\"default train\", linestyle='--', alpha = train_alpha)\n",
" axs[0].plot(range(len(results_optim['train_losses'])), results_optim['train_losses'], color='red', label=\"optim train\", linestyle='--', alpha = train_alpha)\n",
" \n",
" axs[0].set_xlabel('Epochs', fontsize=14)\n",
" axs[0].set_ylabel('Loss', fontsize=14)\n",
" axs[0].set_xscale('linear')\n",
" axs[0].set_yscale('linear')\n",
" max_loss = max(results_default['train_losses']+results_default['val_losses']+results_optim['train_losses']+results_optim['val_losses'])\n",
" axs[0].set_ylim([0, max_loss])\n",
" axs[0].legend(loc=\"upper right\")\n",
" \n",
" # Validation accuracies\n",
" axs[1].plot(range(len(results_default['val_accuracies'])), results_default['val_accuracies'], color='blue', label=\"default val\")\n",
" axs[1].plot(range(len(results_optim['val_accuracies'])), results_optim['val_accuracies'], color='red', label=\"optim val\")\n",
"\n",
" # Training default accuracies\n",
" axs[1].plot(range(len(results_default['train_accuracies'])), results_default['train_accuracies'], color='blue', label=\"default train\", linestyle='--', alpha=train_alpha)\n",
" axs[1].plot(range(len(results_optim['train_accuracies'])), results_optim['train_accuracies'], color='red', label=\"optim train\", linestyle='--', alpha=train_alpha)\n",
" \n",
" axs[1].set_xlabel('Epochs', fontsize=15)\n",
" axs[1].set_ylabel('Accuracy', fontsize=15)\n",
" axs[1].set_xscale('linear')\n",
" axs[1].set_yscale('linear')\n",
" axs[1].set_ylim([0, 100])\n",
" axs[1].legend(loc=\"lower right\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "USjwbaqvfvT9"
},
"source": [
"## Training configuration variables\n",
"For the first run, you can let all the values given by default.\n",
"For the optimized run, you could changing some parameters. \n",
">In particular, you will have to change :\n",
">- the batch_size\n",
">- the learning rate"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "vJRP94hFejjg"
},
"outputs": [],
"source": [
"args = {\n",
" 'batch_size':64,\n",
" 'epochs': 10,\n",
" 'image_size': 224,\n",
" 'learning_rate': 0.001,\n",
" 'momentum': 0.9,\n",
" 'weight_decay': 0.0001,\n",
" 'download': True,\n",
" 'device': torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\"),\n",
" 'dataset_root_dir': os.getcwd(),\n",
"}\n",
"\n",
"#################################################\n",
"############# Modify the code below #############\n",
"#################################################\n",
"args_optim = {\n",
" 'batch_size':64,\n",
" 'epochs': 10,\n",
" 'image_size': 224,\n",
" 'learning_rate': 0.001,\n",
" 'momentum': 0.9,\n",
" 'weight_decay': 0.0001,\n",
" 'download': True,\n",
" 'device': torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\"),\n",
" 'dataset_root_dir': os.getcwd(), \n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "pfQP_RbKAU6N"
},
"source": [
"<details>\n",
"<summary>Spoiler (click to reveal)</summary>\n",
"\n",
"```python\n",
"args_optim = {\n",
" 'batch_size':512,\n",
" 'epochs': 10,\n",
" 'image_size': 224,\n",
" 'learning_rate': 0.001,\n",
" 'momentum': 0.9,\n",
" 'weight_decay': 0.01,\n",
" 'download': True,\n",
" 'device': torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\"),\n",
" 'dataset_root_dir': os.getcwd(), \n",
"}\n",
"``` \n",
"</details>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "b5CbvfOAfnQ9"
},
"source": [
"## Data transformation and augmentation\n",
"Below, we define the transformations to apply to each image when loaded.\n",
"It can serve three main purposes:\n",
"- having the data in the desired format for the model (systematic transformation)\n",
"- correcting/normalizing the data (systematic transformation)\n",
"- artificially increasing the amount of data by transforming the data (random transformation)\n",
"\n",
"Warning : the evaluation dataset should always be the same so you should not apply random transformations to it.\n",
"\n",
"> Enrich the transformations by using the provided by torchvision : https://pytorch.org/vision/0.12/transforms.html\n",
"\n",
"> **Change transform_optim and val_transform_optim only**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "I8d51hBifiDH"
},
"outputs": [],
"source": [
"transform = transforms.Compose([transforms.ToTensor()]) # convert the PIL Image to a tensor\n",
"val_transform = transforms.Compose([transforms.ToTensor()]) # convert the PIL Image to a tensor\n",
" \n",
"#################################################\n",
"############# Modify the code below #############\n",
"#################################################\n",
"transform_optim = transforms.Compose([transforms.ToTensor()]) # convert the PIL Image to a tensor\n",
"val_transform_optim = transforms.Compose([transforms.ToTensor()]) # convert the PIL Image to a tensor"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "VZp4xMdxrJs9"
},
"source": [
"<details>\n",
"<summary>Spoiler</summary>\n",
"\n",
" \n",
"```python\n",
"transform_optim = transforms.Compose([ \n",
" transforms.RandomHorizontalFlip(), # Horizontal Flip - Data Augmentation\n",
" transforms.ToTensor() # convert the PIL Image to a tensor\n",
" ])\n",
"\n",
"val_transform_optim = transforms.Compose([\n",
" transforms.ToTensor() # convert the PIL Image to a tensor\n",
" ])\n",
"``` \n",
"</details>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "rYIkzw02fqnd"
},
"source": [
"## Dataset\n",
"In the cell below, we define the dataset.\n",
"Here we have two subset:\n",
"- a training subset for model optimization\n",
"- a test subset for model evaluation"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "RImKrDEwe-Y7"
},
"outputs": [],
"source": [
"train_dataset = torchvision.datasets.CIFAR10(root=args['dataset_root_dir']+'/CIFAR_10', train=True, download=args['download'], transform=transform)\n",
"\n",
"val_dataset = torchvision.datasets.CIFAR10(root=args['dataset_root_dir']+'/CIFAR_10', train=False, download=args['download'], transform=val_transform)\n",
"\n",
"train_dataset_optim = torchvision.datasets.CIFAR10(root=args_optim['dataset_root_dir']+'/CIFAR_10', train=True, download=args_optim['download'], transform=transform_optim)\n",
"\n",
"val_dataset_optim = torchvision.datasets.CIFAR10(root=args_optim['dataset_root_dir']+'/CIFAR_10', train=False, download=args_optim['download'], transform=val_transform_optim)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "tFMn2WRHgDko"
},
"source": [
"## Dataloader\n",
"The DataLoader class in PyTorch is responsible for loading and batching data from a dataset object, such as a PyTorch tensor or a NumPy array.\n",
"It works by creating a Python iterable over the dataset and yielding a batch of data at each iteration.\n",
"\n",
"Those batches will be fed to the model for training or inference.\n",
"\n",
"The DataLoader class also provides various options for shuffling, batching, and parallelizing the data loading process, making it a useful tool for efficient and flexible data handling in PyTorch.\n",
"> Take a look at the DataLoader documentation : https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader\n",
"\n",
"> Optimize the dataloader by taking advantage of parallelism and smart use of computational ressources :\n",
">- batch_size\n",
">- pin_memory\n",
">- prefetch_factor \n",
">- persistent_workers \n",
">- num_workers"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "r9Mp67_fgIGN"
},
"outputs": [],
"source": [
"train_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n",
" batch_size=args['batch_size'],\n",
" shuffle=True,\n",
" drop_last=True)\n",
"\n",
"val_loader = torch.utils.data.DataLoader(dataset=val_dataset, \n",
" batch_size=args['batch_size'],\n",
" shuffle=False,\n",
" drop_last=True)\n",
"\n",
"#################################################\n",
"############# Modify the code below #############\n",
"#################################################\n",
"train_loader_optim = torch.utils.data.DataLoader(dataset=train_dataset,\n",
" batch_size=args_optim['batch_size'],\n",
" shuffle=True,\n",
" drop_last=True)\n",
"\n",
"val_loader_optim = torch.utils.data.DataLoader(dataset=val_dataset, \n",
" batch_size=args_optim['batch_size'],\n",
" shuffle=False,\n",
" drop_last=True)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "mvMxD20VNOU8"
},
"outputs": [],
"source": [
"%timeit -r 1 -n 1 iter_dataloader(train_loader, 1, args)\n",
"%timeit -r 1 -n 1 iter_dataloader(train_loader_optim, 1, args_optim)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Vegex5s0gIVF"
},
"source": [
"<details>\n",
"<summary>Spoiler</summary>\n",
"WIP : Quelques explications\n",
"\n",
"```python\n",
"train_loader_optim = torch.utils.data.DataLoader(dataset=train_dataset_optim,\n",
" batch_size=args_optim['batch_size'],\n",
" shuffle=True,\n",
" drop_last=True,\n",
" num_workers=10,\n",
" persistent_workers=True,\n",
" pin_memory=True,\n",
" prefetch_factor=10)\n",
"\n",
"val_loader_optim = torch.utils.data.DataLoader(dataset=val_dataset_optim, \n",
" batch_size=args_optim['batch_size'],\n",
" shuffle=False,\n",
" drop_last=True,\n",
" num_workers=10,\n",
" persistent_workers=True,\n",
" pin_memory=True,\n",
" prefetch_factor=10)\n",
"``` \n",
"</details>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2_yVrvKvgIt0"
},
"source": [
"## Model\n",
"\n",
"> Do not forget to verify that you use the right compute ressources for your model\n",
"\n",
"> By default, the model resnet18 is initialized with random weights but you could try using a pretrained model : https://pytorch.org/vision/main/models/generated/torchvision.models.resnet18.html#torchvision.models.ResNet18_Weights"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "NCQgZOx6gI6Q"
},
"outputs": [],
"source": [
"model = models.resnet18()\n",
"model = model.to(args['device'])\n",
"model.name = 'Resnet-18'\n",
"print(\"Stock model on device:\", next(model.parameters()).device)\n",
"#################################################\n",
"############# Modify the code below #############\n",
"#################################################\n",
"model_optim = models.resnet18()\n",
"model_optim = model_optim.to(args_optim['device'])\n",
"model_optim.name = 'Resnet-18'\n",
"print(\"Optimized model on device:\", next(model_optim.parameters()).device)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "p4umlBOmghZX"
},
"source": [
"<details>\n",
"<summary>Spoiler</summary>\n",
" \n",
"```python\n",
"model_optim = models.resnet18(ResNet18_Weights)\n",
"model_optim = model_optim.to(args_optim['device'])\n",
"model_optim.name = 'Resnet-18'\n",
"print(\"Optimized model on device:\", next(model_optim.parameters()).device)\n",
"``` \n",
"</details>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Ur1uA38ugiBl"
},
"source": [
"## Loss\n",
"We use a standart loss for classification.\n",
"\n",
"For the comparison, if you change the loss, change it for both.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "sxSZEKKogiJe"
},
"outputs": [],
"source": [
"criterion = torch.nn.CrossEntropyLoss()\n",
"criterion_optim = torch.nn.CrossEntropyLoss()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "qJadxpf_giT4"
},
"source": [
"## Optimizer\n",
"\n",
"> In order to speed up the training, you can try to use a different optimizer: https://pytorch.org/docs/stable/optim.html#base-class"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "3fsqrktLgiaJ"
},
"outputs": [],
"source": [
"optimizer = torch.optim.SGD(model.parameters(), args['learning_rate'], args['momentum'], args['weight_decay'])\n",
"#################################################\n",
"############# Modify the code below #############\n",
"#################################################\n",
"optimizer_optim = torch.optim.SGD(model.parameters(), args_optim['learning_rate'], args_optim['momentum'], args_optim['weight_decay'])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ZEcyEt1Ig21T"
},
"source": [
"<details>\n",
"<summary>Spoiler</summary>\n",
"\n",
"```python\n",
"optimizer_optim = torch.optim.AdamW(model_optim.parameters(), lr = args_optim['learning_rate'], weight_decay=args_optim['weight_decay'])\n",
"```\n",
"</details>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3wcKevBct--P"
},
"source": [
"## Learning rate scheduler\n",
"In order to adjust the learning rate over iterations/epochs, we can make use of a learning rate scheduler.\n",
"\n",
"To use a LR scheduler, you will need to :\n",
"- instantiate the scheduler (in the coding cell below)\n",
"- adapt the training loop (in the \"Training\" section)\n",
"\n",
"Take a look at this page : https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate which: \n",
"- describes how to use a scheduler (warning : some scheduler are updated at a step level and others at an epoch level)\n",
"- lists the available schedulers (you could also create your own starting from the _LRScheduler class)\n",
"\n",
"> **You can define your scheduler here.**\n",
"\n",
"> **You will have to modify the training loop later on.**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ISanTSFWuBps"
},
"outputs": [],
"source": [
"scheduler = None\n",
"#################################################\n",
"############# Modify the code below #############\n",
"#################################################\n",
"scheduler_optim = None"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "KvnPRnuJvjVx"
},
"source": [
"<details>\n",
"<summary>Spoiler</summary>\n",
" \n",
"```python\n",
"scheduler_optim = torch.optim.lr_scheduler.OneCycleLR(optimizer_optim, \n",
" max_lr=args_optim['learning_rate'], \n",
" steps_per_epoch = len(train_loader_optim), \n",
" epochs=args_optim['epochs'])\n",
"``` \n",
"</details>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "YxPlz4U3g9Yv"
},
"source": [
"## Model training (reference performances)\n",
"Once we have all our main actors, we can setup the stage that is our training loop.\n",
"\n",
"Below is used a typical loop as you can find in https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html\n",
"> **Run it a first time to have a performance baseline with all the default values.**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cy1QzZxwNOVH"
},
"outputs": [],
"source": [
"results_default = train_default(train_loader, val_loader, model, optimizer, criterion, args)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "7vU3uot9v3hc"
},
"source": [
"## Speeding up the hyperparameter search : Learning Rate Finder\n",
"Wether we are using a scheduler or not, we need to determine either : \n",
"- the constant learning rate you want to use, \n",
"- or the maximum learning rate used by the scheduler.\n",
"\n",
"If you are in the first situation, you just want a good all-rounder learning rate to have a relatively fast conversion and minimize the oscillations at the end of the convergence.\n",
"\n",
"In the second situation, you can focus more on having the fastest inital convergence as the oscillations will be generally taken care by a decreasing learning rate strategy. Thus, we want the highest maximum learning rate possible.\n",
"\n",
"It would be ideal to find the best learning rate quickly in order to speedup our hyperparameter search.\n",
"Various strategy more or less complex exists to find an estimate of this value.\n",
"Below, we try to find the learning rate by doing a few steps on a range of learning rates. We evaluate each learning rate to determine the best one to choose for our full training.\n",
"\n",
"> **As this step can take quite some time, we provided you with some values for the default config which you are not supposed to change anyway. You can find them in the next spoiler**\n",
"\n",
"> **Uncomment explore_lrs to rerun the exploration, otherwise you can reuse the given values.**\n",
"\n",
"> **Be careful to re-run this cell to reset the model and optimizer,... to have a \"fresh\" exploration each time**\n",
"\n",
"> **Also if you change the optimizer for the optimized run, change it also here to find the best learning rate for that optimizer.** Or rerun the cell where you defined it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "kG45YwwY5Hut"
},
"outputs": [],
"source": [
"lrs, lrs_losses, lrs_metric_avg, lrs_metric_var = explore_lrs(train_loader_optim,\n",
" model_optim, \n",
" optimizer_optim,\n",
" args_optim,\n",
" min_learning_rate_power=-6, \n",
" max_learning_rate_power = 1,\n",
" num_lrs=8,\n",
" steps_per_lr=100) "
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "pDmkRbleNOVL"
},
"source": [
"<details>\n",
"<summary>Spoiler</summary>\n",
" \n",
"```python\n",
"lrs=[1.e-06, 1.e-05, 1.e-04, 1.e-03, 1.e-02, 1.e-01, 1.e+00, 1.e+01]\n",
"lrs_losses= [7.502097129821777, 7.22658634185791, 5.24326229095459, 1.7600191831588745, 1.4037541151046753, 2.136382579803467, 2.1029751300811768, 446.49951171875]\n",
"lrs_metric_avg=[0.0017601490020751954, -0.005245075225830078, -0.041641921997070314, -0.07478624820709229, -0.007052739858627319, 0.04763659238815308, 0.03924872875213623, 9.939403522014619]\n",
"lrs_metric_var=[0.0006510000222988311, 0.0004144988674492198, 0.000668689274974986, 0.013876865854565344, 0.001481160611942387, 0.3384368026131311, 0.8817071610439394, 2157852536609.2454]\n",
"``` \n",
"</details>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gpFPWNZXv670"
},
"outputs": [],
"source": [
"plot_eval(lrs, lrs_losses, lrs_metric_avg, lrs_metric_var)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "pVw14RZ9NOVO"
},
"source": [
"## Optimize the training loop\n",
"\n",
"> Adapt the dataset transformations, batch_size & dataloader, lr & lr_scheduler, and optimizer in order to achieve better classification results in less time. \n",
"\n",
"> Change this training loop to include:\n",
"> - a learning rate scheduler : https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate\n",
"> - a strategy such as early stopping or patience : https://www.kaggle.com/code/akhileshrai/tutorial-early-stopping-vanilla-rnn-pytorch?scriptVersionId=26440051&cellId=10#4.-Early-Stopping\n",
"\n",
"> **Also think about changing the call to the function if you added arguments.**\n",
"\n",
"> For you, we added automatic mixed precision which will be seen in the next course\n",
"\n",
"> **BEFORE RUNNING, WE NEED TO REINITIALIZE THE MODEL, OPTIMIZER AND SCHEDULER FOR A FAIR FIGHT. Rewrite below the changes you have brought to them.**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "hF-p2CCsNOVO"
},
"outputs": [],
"source": [
"model_optim = models.resnet18().to(args_optim['device'])\n",
"model_optim.name = 'Resnet-18'\n",
"optimizer_optim = torch.optim.SGD(model_optim.parameters(), args_optim['learning_rate'], args_optim['momentum'], args_optim['weight_decay'])\n",
"scheduler_optim = None"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "q79Y1wzENOVQ"
},
"outputs": [],
"source": [
"def train_optim(train_loader, val_loader, model, optimizer, criterion, args):\n",
" '''\n",
" The default simple training loop\n",
" '''\n",
" train_losses = []\n",
" train_accuracies = []\n",
" val_losses = []\n",
" val_accuracies = []\n",
" time_start = time.time()\n",
" for epoch in range(args['epochs']):\n",
" print(\"Epoch \", epoch)\n",
" for i, (images, labels) in enumerate(train_loader):\n",
" # distribution of images and labels to all GPUs\n",
" images = images.to(args['device'], non_blocking=True)\n",
" labels = labels.to(args['device'], non_blocking=True)\n",
" \n",
" # Zero the parameter gradients\n",
" optimizer.zero_grad()\n",
"\n",
" # Forward pass\n",
" outputs = model(images)\n",
" loss = criterion(outputs, labels)\n",
"\n",
" # Backward pass\n",
" loss.backward()\n",
"\n",
" # Optimize\n",
" optimizer.step()\n",
"\n",
" # Evaluate at the end of the epoch on the train set\n",
" train_loss, train_accuracy = evaluate(train_loader, model, criterion, args)\n",
" print(\"\\t Train loss : \", train_loss, \"& Train accuracy : \", train_accuracy)\n",
" train_losses.append(train_loss)\n",
" train_accuracies.append(train_accuracy) \n",
" \n",
" # Evaluate at the end of the epoch on the val set\n",
" val_loss, val_accuracy = evaluate(val_loader, model, criterion, args)\n",
" print(\"\\t Validation loss : \", val_loss, \"& Validation accuracy : \", val_accuracy)\n",
" val_losses.append(val_loss)\n",
" val_accuracies.append(val_accuracy)\n",
" duration = time.time() - time_start\n",
" print('Finished Training in:', duration, 'seconds with mean epoch duration:', duration/args['epochs'], ' seconds')\n",
" results = {'model':model,\n",
" 'train_losses': train_losses,\n",
" 'train_accuracies': train_accuracies,\n",
" 'val_losses': val_losses,\n",
" 'val_accuracies': val_accuracies,\n",
" 'duration':duration}\n",
" return results\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Z_T19pdUNOVR"
},
"source": [
"<details>\n",
"<summary>Spoiler</summary>\n",
" \n",
"```python\n",
"def train_optim(train_loader, val_loader, model, optimizer, criterion, scheduler, args):\n",