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

#869 Add DagsHub Logger to Super Gradients

Merged
Ghost merged 1 commits into Deci-AI:master from timho102003:dagshub_logger
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
  1. import os
  2. import torch
  3. import numpy as np
  4. import pkg_resources
  5. from super_gradients.training import utils as core_utils
  6. from super_gradients.training.utils.utils import move_state_dict_to_device
  7. class ModelWeightAveraging:
  8. """
  9. Utils class for managing the averaging of the best several snapshots into a single model.
  10. A snapshot dictionary file and the average model will be saved / updated at every epoch and evaluated only when
  11. training is completed. The snapshot file will only be deleted upon completing the training.
  12. The snapshot dict will be managed on cpu.
  13. """
  14. def __init__(
  15. self,
  16. ckpt_dir,
  17. greater_is_better,
  18. source_ckpt_folder_name=None,
  19. metric_to_watch="acc",
  20. metric_idx=1,
  21. load_checkpoint=False,
  22. number_of_models_to_average=10,
  23. ):
  24. """
  25. Init the ModelWeightAveraging
  26. :param checkpoint_dir: the directory where the checkpoints are saved
  27. :param metric_to_watch: monitoring loss or acc, will be identical to that which determines best_model
  28. :param metric_idx:
  29. :param load_checkpoint: whether to load pre-existing snapshot dict.
  30. :param number_of_models_to_average: number of models to average
  31. """
  32. if source_ckpt_folder_name is not None:
  33. source_ckpt_file = os.path.join(source_ckpt_folder_name, "averaging_snapshots.pkl")
  34. source_ckpt_file = pkg_resources.resource_filename("checkpoints", source_ckpt_file)
  35. self.averaging_snapshots_file = os.path.join(ckpt_dir, "averaging_snapshots.pkl")
  36. self.number_of_models_to_average = number_of_models_to_average
  37. self.metric_to_watch = metric_to_watch
  38. self.metric_idx = metric_idx
  39. self.greater_is_better = greater_is_better
  40. # if continuing training, copy previous snapshot dict if exist
  41. if load_checkpoint and source_ckpt_folder_name is not None and os.path.isfile(source_ckpt_file):
  42. averaging_snapshots_dict = core_utils.load_checkpoint(
  43. ckpt_destination_dir=ckpt_dir,
  44. source_ckpt_folder_name=source_ckpt_folder_name,
  45. ckpt_filename="averaging_snapshots.pkl",
  46. load_weights_only=False,
  47. overwrite_local_ckpt=True,
  48. )
  49. else:
  50. averaging_snapshots_dict = {"snapshot" + str(i): None for i in range(self.number_of_models_to_average)}
  51. # if metric to watch is acc, hold a zero array, if loss hold inf array
  52. if self.greater_is_better:
  53. averaging_snapshots_dict["snapshots_metric"] = -1 * np.inf * np.ones(self.number_of_models_to_average)
  54. else:
  55. averaging_snapshots_dict["snapshots_metric"] = np.inf * np.ones(self.number_of_models_to_average)
  56. torch.save(averaging_snapshots_dict, self.averaging_snapshots_file)
  57. def update_snapshots_dict(self, model, validation_results_tuple):
  58. """
  59. Update the snapshot dict and returns the updated average model for saving
  60. :param model: the latest model
  61. :param validation_results_tuple: performance of the latest model
  62. """
  63. averaging_snapshots_dict = self._get_averaging_snapshots_dict()
  64. # IF CURRENT MODEL IS BETTER, TAKING HIS PLACE IN ACC LIST AND OVERWRITE THE NEW AVERAGE
  65. require_update, update_ind = self._is_better(averaging_snapshots_dict, validation_results_tuple)
  66. if require_update:
  67. # moving state dict to cpu
  68. new_sd = model.state_dict()
  69. new_sd = move_state_dict_to_device(new_sd, "cpu")
  70. averaging_snapshots_dict["snapshot" + str(update_ind)] = new_sd
  71. averaging_snapshots_dict["snapshots_metric"][update_ind] = validation_results_tuple[self.metric_idx]
  72. return averaging_snapshots_dict
  73. def get_average_model(self, model, validation_results_tuple=None):
  74. """
  75. Returns the averaged model
  76. :param model: will be used to determine arch
  77. :param validation_results_tuple: if provided, will update the average model before returning
  78. :param target_device: if provided, return sd on target device
  79. """
  80. # If validation tuple is provided, update the average model
  81. if validation_results_tuple is not None:
  82. averaging_snapshots_dict = self.update_snapshots_dict(model, validation_results_tuple)
  83. else:
  84. averaging_snapshots_dict = self._get_averaging_snapshots_dict()
  85. torch.save(averaging_snapshots_dict, self.averaging_snapshots_file)
  86. average_model_sd = averaging_snapshots_dict["snapshot0"]
  87. for n_model in range(1, self.number_of_models_to_average):
  88. if averaging_snapshots_dict["snapshot" + str(n_model)] is not None:
  89. net_sd = averaging_snapshots_dict["snapshot" + str(n_model)]
  90. # USING MOVING AVERAGE
  91. for key in average_model_sd:
  92. average_model_sd[key] = torch.true_divide(average_model_sd[key] * n_model + net_sd[key], (n_model + 1))
  93. return average_model_sd
  94. def cleanup(self):
  95. """
  96. Delete snapshot file when reaching the last epoch
  97. """
  98. os.remove(self.averaging_snapshots_file)
  99. def _is_better(self, averaging_snapshots_dict, validation_results_tuple):
  100. """
  101. Determines if the new model is better according to the specified metrics
  102. :param averaging_snapshots_dict: snapshot dict
  103. :param validation_results_tuple: latest model performance
  104. """
  105. snapshot_metric_array = averaging_snapshots_dict["snapshots_metric"]
  106. val = validation_results_tuple[self.metric_idx]
  107. if self.greater_is_better:
  108. update_ind = np.argmin(snapshot_metric_array)
  109. else:
  110. update_ind = np.argmax(snapshot_metric_array)
  111. if (self.greater_is_better and val > snapshot_metric_array[update_ind]) or (not self.greater_is_better and val < snapshot_metric_array[update_ind]):
  112. return True, update_ind
  113. return False, None
  114. def _get_averaging_snapshots_dict(self):
  115. return torch.load(self.averaging_snapshots_file)
Discard
Tip!

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