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.3 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
  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, training_params=HpmStruct(max_epochs=10), checkpoints_dir_path=cls.sg_model.checkpoints_dir_path)
  47. cls.sg_model.save_checkpoint()
  48. @classmethod
  49. def tearDownClass(cls):
  50. if os.path.isdir(cls.temp_working_file_dir):
  51. shutil.rmtree(cls.temp_working_file_dir)
  52. @classmethod
  53. def change_state_dict_keys(self, state_dict):
  54. new_ckpt_dict = {}
  55. for i, (ckpt_key, ckpt_val) in enumerate(state_dict.items()):
  56. new_ckpt_dict[i] = ckpt_val
  57. return new_ckpt_dict
  58. def check_models_have_same_weights(self, model_1, model_2):
  59. model_1, model_2 = model_1.to('cpu'), model_2.to('cpu')
  60. models_differ = 0
  61. for key_item_1, key_item_2 in zip(model_1.state_dict().items(), model_2.state_dict().items()):
  62. if torch.equal(key_item_1[1], key_item_2[1]):
  63. pass
  64. else:
  65. models_differ += 1
  66. if (key_item_1[0] == key_item_2[0]):
  67. print('Mismtach found at', key_item_1[0])
  68. else:
  69. raise Exception
  70. if models_differ == 0:
  71. return True
  72. else:
  73. return False
  74. def test_strict_load_on(self):
  75. # Define Model
  76. new_torch_net = Net()
  77. # Make sure we initialized a model with different weights
  78. assert not self.check_models_have_same_weights(new_torch_net, self.original_torch_net)
  79. # Build the SgModel and load the checkpoint
  80. model = SgModel(self.experiment_name, model_checkpoints_location='local',
  81. ckpt_name='ckpt_latest_weights_only.pth')
  82. model.build_model(new_torch_net, arch_params={'num_classes': 10}, strict_load=StrictLoad.ON,
  83. load_checkpoint=True)
  84. # Assert the weights were loaded correctly
  85. assert self.check_models_have_same_weights(model.net, self.original_torch_net)
  86. def test_strict_load_off(self):
  87. # Define Model
  88. new_torch_net = Net()
  89. # Make sure we initialized a model with different weights
  90. assert not self.check_models_have_same_weights(new_torch_net, self.original_torch_net)
  91. # Build the SgModel and load the checkpoint
  92. model = SgModel(self.experiment_name, model_checkpoints_location='local',
  93. ckpt_name='ckpt_latest_weights_only.pth')
  94. model.build_model(new_torch_net, arch_params={'num_classes': 10}, strict_load=StrictLoad.OFF,
  95. load_checkpoint=True)
  96. # Assert the weights were loaded correctly
  97. assert self.check_models_have_same_weights(model.net, self.original_torch_net)
  98. def test_strict_load_no_key_matching_external_checkpoint(self):
  99. # Define Model
  100. new_torch_net = Net()
  101. # Make sure we initialized a model with different weights
  102. assert not self.check_models_have_same_weights(new_torch_net, self.original_torch_net)
  103. # Build the SgModel and load the checkpoint
  104. model = SgModel(self.experiment_name, model_checkpoints_location='local')
  105. model.build_model(new_torch_net, arch_params={'num_classes': 10}, strict_load=StrictLoad.NO_KEY_MATCHING,
  106. external_checkpoint_path=self.checkpoint_diff_keys_path, load_checkpoint=True)
  107. # Assert the weights were loaded correctly
  108. assert self.check_models_have_same_weights(model.net, self.original_torch_net)
  109. def test_strict_load_no_key_matching_sg_checkpoint(self):
  110. # Define Model
  111. new_torch_net = Net()
  112. # Make sure we initialized a model with different weights
  113. assert not self.check_models_have_same_weights(new_torch_net, self.original_torch_net)
  114. # Build the SgModel and load the checkpoint
  115. model = SgModel(self.experiment_name, model_checkpoints_location='local',
  116. ckpt_name='ckpt_latest_weights_only.pth')
  117. model.build_model(new_torch_net, arch_params={'num_classes': 10}, strict_load=StrictLoad.NO_KEY_MATCHING,
  118. load_checkpoint=True)
  119. # Assert the weights were loaded correctly
  120. assert self.check_models_have_same_weights(model.net, self.original_torch_net)
  121. if __name__ == '__main__':
  122. unittest.main()
Tip!

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

Comments

Loading...