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

strictload_enum_test.py 6.7 KB

You have to be logged in to leave a comment. Sign In
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
  1. import shutil
  2. import tempfile
  3. import unittest
  4. import os
  5. from super_gradients.common.sg_loggers import BaseSGLogger
  6. from super_gradients.training import SgModel
  7. import torch
  8. import torch.nn as nn
  9. import torch.nn.functional as F
  10. from super_gradients.training.sg_model.sg_model import StrictLoad
  11. from super_gradients.training.utils import HpmStruct
  12. class Net(nn.Module):
  13. def __init__(self):
  14. super(Net, self).__init__()
  15. self.conv1 = nn.Conv2d(3, 6, 3)
  16. self.pool = nn.MaxPool2d(2, 2)
  17. self.conv2 = nn.Conv2d(6, 16, 3)
  18. self.fc1 = nn.Linear(16 * 3 * 3, 120)
  19. self.fc2 = nn.Linear(120, 84)
  20. self.fc3 = nn.Linear(84, 10)
  21. def forward(self, x):
  22. x = self.pool(F.relu(self.conv1(x)))
  23. x = self.pool(F.relu(self.conv2(x)))
  24. x = x.view(-1, 16 * 3 * 3)
  25. x = F.relu(self.fc1(x))
  26. x = F.relu(self.fc2(x))
  27. x = self.fc3(x)
  28. return x
  29. class StrictLoadEnumTest(unittest.TestCase):
  30. @classmethod
  31. def setUpClass(cls):
  32. cls.temp_working_file_dir = tempfile.TemporaryDirectory(prefix='strict_load_test').name
  33. if not os.path.isdir(cls.temp_working_file_dir):
  34. os.mkdir(cls.temp_working_file_dir)
  35. cls.experiment_name = 'load_checkpoint_test'
  36. cls.checkpoint_diff_keys_name = 'strict_load_test_diff_keys.pth'
  37. cls.checkpoint_diff_keys_path = cls.temp_working_file_dir + '/' + cls.checkpoint_diff_keys_name
  38. # Setup the model
  39. cls.original_torch_net = Net()
  40. # Save the model's state_dict checkpoint with different keys
  41. torch.save(cls.change_state_dict_keys(cls.original_torch_net.state_dict()), cls.checkpoint_diff_keys_path)
  42. # Save the model's state_dict checkpoint in SgModel format
  43. cls.sg_model = SgModel("load_checkpoint_test", model_checkpoints_location='local') # Saves in /checkpoints
  44. cls.sg_model.build_model(cls.original_torch_net, arch_params={'num_classes': 10})
  45. # FIXME: after uniting init and build_model we should remove this
  46. cls.sg_model.sg_logger = BaseSGLogger('project_name', 'load_checkpoint_test', 'local', resumed=False,
  47. training_params=HpmStruct(max_epochs=10),
  48. checkpoints_dir_path=cls.sg_model.checkpoints_dir_path)
  49. cls.sg_model._save_checkpoint()
  50. @classmethod
  51. def tearDownClass(cls):
  52. if os.path.isdir(cls.temp_working_file_dir):
  53. shutil.rmtree(cls.temp_working_file_dir)
  54. @classmethod
  55. def change_state_dict_keys(self, state_dict):
  56. new_ckpt_dict = {}
  57. for i, (ckpt_key, ckpt_val) in enumerate(state_dict.items()):
  58. new_ckpt_dict[i] = ckpt_val
  59. return new_ckpt_dict
  60. def check_models_have_same_weights(self, model_1, model_2):
  61. model_1, model_2 = model_1.to('cpu'), model_2.to('cpu')
  62. models_differ = 0
  63. for key_item_1, key_item_2 in zip(model_1.state_dict().items(), model_2.state_dict().items()):
  64. if torch.equal(key_item_1[1], key_item_2[1]):
  65. pass
  66. else:
  67. models_differ += 1
  68. if (key_item_1[0] == key_item_2[0]):
  69. print('Mismtach found at', key_item_1[0])
  70. else:
  71. raise Exception
  72. if models_differ == 0:
  73. return True
  74. else:
  75. return False
  76. def test_strict_load_on(self):
  77. # Define Model
  78. new_torch_net = Net()
  79. # Make sure we initialized a model with different weights
  80. assert not self.check_models_have_same_weights(new_torch_net, self.original_torch_net)
  81. # Build the SgModel and load the checkpoint
  82. model = SgModel(self.experiment_name, model_checkpoints_location='local',
  83. ckpt_name='ckpt_latest_weights_only.pth')
  84. model.build_model(new_torch_net, arch_params={'num_classes': 10},
  85. checkpoint_params={'strict_load': StrictLoad.ON,
  86. 'load_checkpoint': True})
  87. # Assert the weights were loaded correctly
  88. assert self.check_models_have_same_weights(model.net, self.original_torch_net)
  89. def test_strict_load_off(self):
  90. # Define Model
  91. new_torch_net = Net()
  92. # Make sure we initialized a model with different weights
  93. assert not self.check_models_have_same_weights(new_torch_net, self.original_torch_net)
  94. # Build the SgModel and load the checkpoint
  95. model = SgModel(self.experiment_name, model_checkpoints_location='local',
  96. ckpt_name='ckpt_latest_weights_only.pth')
  97. model.build_model(new_torch_net, arch_params={'num_classes': 10},
  98. checkpoint_params={'strict_load': StrictLoad.OFF,
  99. 'load_checkpoint': True})
  100. # Assert the weights were loaded correctly
  101. assert self.check_models_have_same_weights(model.net, self.original_torch_net)
  102. def test_strict_load_no_key_matching_external_checkpoint(self):
  103. # Define Model
  104. new_torch_net = Net()
  105. # Make sure we initialized a model with different weights
  106. assert not self.check_models_have_same_weights(new_torch_net, self.original_torch_net)
  107. # Build the SgModel and load the checkpoint
  108. model = SgModel(self.experiment_name, model_checkpoints_location='local')
  109. model.build_model(new_torch_net, arch_params={'num_classes': 10},
  110. checkpoint_params={'strict_load': StrictLoad.NO_KEY_MATCHING,
  111. 'external_checkpoint_path': self.checkpoint_diff_keys_path,
  112. 'load_checkpoint': True})
  113. # Assert the weights were loaded correctly
  114. assert self.check_models_have_same_weights(model.net, self.original_torch_net)
  115. def test_strict_load_no_key_matching_sg_checkpoint(self):
  116. # Define Model
  117. new_torch_net = Net()
  118. # Make sure we initialized a model with different weights
  119. assert not self.check_models_have_same_weights(new_torch_net, self.original_torch_net)
  120. # Build the SgModel and load the checkpoint
  121. model = SgModel(self.experiment_name, model_checkpoints_location='local',
  122. ckpt_name='ckpt_latest_weights_only.pth')
  123. model.build_model(new_torch_net, arch_params={'num_classes': 10},
  124. checkpoint_params={'strict_load': StrictLoad.NO_KEY_MATCHING,
  125. 'load_checkpoint': True})
  126. # Assert the weights were loaded correctly
  127. assert self.check_models_have_same_weights(model.net, self.original_torch_net)
  128. if __name__ == '__main__':
  129. unittest.main()
Tip!

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

Comments

Loading...