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

#581 Bug/sg 512 shuffle bugfix in recipe datalaoders

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:bug/SG-512_shuffle_bugfix_in_recipe_datalaoders
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
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
  1. from pathlib import Path
  2. from typing import Tuple, Type, Optional
  3. import hydra
  4. import torch
  5. from super_gradients.common import StrictLoad
  6. from super_gradients.common.plugins.deci_client import DeciClient, client_enabled
  7. from super_gradients.training import utils as core_utils
  8. from super_gradients.training.models import SgModule
  9. from super_gradients.training.models.all_architectures import ARCHITECTURES
  10. from super_gradients.training.pretrained_models import PRETRAINED_NUM_CLASSES
  11. from super_gradients.training.utils import HpmStruct
  12. from super_gradients.training.utils.checkpoint_utils import (
  13. load_checkpoint_to_model,
  14. load_pretrained_weights,
  15. read_ckpt_state_dict,
  16. load_pretrained_weights_local,
  17. )
  18. from super_gradients.common.abstractions.abstract_logger import get_logger
  19. from super_gradients.training.utils.sg_trainer_utils import get_callable_param_names
  20. logger = get_logger(__name__)
  21. def get_architecture(model_name: str, arch_params: HpmStruct, download_required_code: bool = True) -> Tuple[Type[torch.nn.Module], HpmStruct, str, bool]:
  22. """
  23. Get the corresponding architecture class.
  24. :param model_name: Define the model's architecture from models/ALL_ARCHITECTURES
  25. :param arch_params: Architecture hyper parameters. e.g.: block, num_blocks, etc.
  26. :param download_required_code: if model is not found in SG and is downloaded from a remote client, overriding this parameter with False
  27. will prevent additional code from being downloaded. This affects only models from remote client.
  28. :return:
  29. - architecture_cls: Class of the model
  30. - arch_params: Might be updated if loading from remote deci lab
  31. - pretrained_weights_path: path to the pretrained weights from deci lab (None for local models).
  32. - is_remote: True if loading from remote deci lab
  33. """
  34. pretrained_weights_path = None
  35. is_remote = False
  36. if not isinstance(model_name, str):
  37. raise ValueError("Parameter model_name is expected to be a string.")
  38. elif model_name not in ARCHITECTURES.keys():
  39. if client_enabled:
  40. logger.info(f'The required model, "{model_name}", was not found in SuperGradients. Trying to load a model from remote deci-lab')
  41. deci_client = DeciClient()
  42. _arch_params = deci_client.get_model_arch_params(model_name)
  43. if download_required_code:
  44. deci_client.download_and_load_model_additional_code(model_name, Path.cwd())
  45. if _arch_params is None:
  46. raise ValueError(
  47. f'The required model, "{model_name}", was not found in SuperGradients and remote deci-lab. See docs or '
  48. f"all_architectures.py for supported model names."
  49. )
  50. _arch_params = hydra.utils.instantiate(_arch_params)
  51. pretrained_weights_path = deci_client.get_model_weights(model_name)
  52. model_name = _arch_params["model_name"]
  53. del _arch_params["model_name"]
  54. _arch_params = HpmStruct(**_arch_params)
  55. _arch_params.override(**arch_params.to_dict())
  56. arch_params, is_remote = _arch_params, True
  57. else:
  58. raise ValueError(
  59. f'The required model, "{model_name}", was not found in SuperGradients. See docs or all_architectures.py for supported model names.'
  60. )
  61. return ARCHITECTURES[model_name], arch_params, pretrained_weights_path, is_remote
  62. def instantiate_model(
  63. model_name: str, arch_params: dict, num_classes: int, pretrained_weights: str = None, download_required_code: bool = True
  64. ) -> torch.nn.Module:
  65. """
  66. Instantiates nn.Module according to architecture and arch_params, and handles pretrained weights and the required
  67. module manipulation (i.e head replacement).
  68. :param model_name: Define the model's architecture from models/ALL_ARCHITECTURES
  69. :param arch_params: Architecture hyper parameters. e.g.: block, num_blocks, etc.
  70. :param num_classes: Number of classes (defines the net's structure).
  71. If None is given, will try to derrive from pretrained_weight's corresponding dataset.
  72. :param pretrained_weights: Describe the dataset of the pretrained weights (for example "imagenent")
  73. :param download_required_code: if model is not found in SG and is downloaded from a remote client, overriding this parameter with False
  74. will prevent additional code from being downloaded. This affects only models from remote client.
  75. :return: Instantiated model i.e torch.nn.Module, architecture_class (will be none when architecture is not str)
  76. """
  77. if arch_params is None:
  78. arch_params = {}
  79. arch_params = core_utils.HpmStruct(**arch_params)
  80. architecture_cls, arch_params, pretrained_weights_path, is_remote = get_architecture(model_name, arch_params, download_required_code)
  81. if not issubclass(architecture_cls, SgModule):
  82. net = architecture_cls(**arch_params.to_dict(include_schema=False))
  83. else:
  84. if core_utils.get_param(arch_params, "num_classes"):
  85. logger.warning(
  86. "Passing num_classes through arch_params is deprecated and will be removed in the next version. " "Pass num_classes explicitly to models.get"
  87. )
  88. num_classes = num_classes or arch_params.num_classes
  89. if num_classes is not None:
  90. arch_params.override(num_classes=num_classes)
  91. if pretrained_weights is None and num_classes is None:
  92. raise ValueError("num_classes or pretrained_weights must be passed to determine net's structure.")
  93. if pretrained_weights:
  94. num_classes_new_head = core_utils.get_param(arch_params, "num_classes", PRETRAINED_NUM_CLASSES[pretrained_weights])
  95. arch_params.num_classes = PRETRAINED_NUM_CLASSES[pretrained_weights]
  96. # Most of the SG models work with a single params names "arch_params" of type HpmStruct, but a few take **kwargs instead
  97. if "arch_params" not in get_callable_param_names(architecture_cls):
  98. net = architecture_cls(**arch_params.to_dict(include_schema=False))
  99. else:
  100. net = architecture_cls(arch_params=arch_params)
  101. if pretrained_weights:
  102. if is_remote:
  103. load_pretrained_weights_local(net, model_name, pretrained_weights_path)
  104. else:
  105. load_pretrained_weights(net, model_name, pretrained_weights)
  106. if num_classes_new_head != arch_params.num_classes:
  107. net.replace_head(new_num_classes=num_classes_new_head)
  108. arch_params.num_classes = num_classes_new_head
  109. return net
  110. def get(
  111. model_name: str,
  112. arch_params: Optional[dict] = None,
  113. num_classes: int = None,
  114. strict_load: StrictLoad = StrictLoad.NO_KEY_MATCHING,
  115. checkpoint_path: str = None,
  116. pretrained_weights: str = None,
  117. load_backbone: bool = False,
  118. download_required_code: bool = True,
  119. checkpoint_num_classes: int = None,
  120. ) -> SgModule:
  121. """
  122. :param model_name: Defines the model's architecture from models/ALL_ARCHITECTURES
  123. :param arch_params: Architecture hyper parameters. e.g.: block, num_blocks, etc.
  124. :param num_classes: Number of classes (defines the net's structure).
  125. If None is given, will try to derrive from pretrained_weight's corresponding dataset.
  126. :param strict_load: See super_gradients.common.data_types.enum.strict_load.StrictLoad class documentation for details
  127. (default=NO_KEY_MATCHING to suport SG trained checkpoints)
  128. :param checkpoint_path: The path to the external checkpoint to be loaded. Can be absolute or relative (ie: path/to/checkpoint.pth).
  129. If provided, will automatically attempt to load the checkpoint.
  130. :param pretrained_weights: Describe the dataset of the pretrained weights (for example "imagenent").
  131. :param load_backbone: Load the provided checkpoint to model.backbone instead of model.
  132. :param download_required_code: if model is not found in SG and is downloaded from a remote client, overriding this parameter with False
  133. will prevent additional code from being downloaded. This affects only models from remote client.
  134. :param checkpoint_num_classes: num_classes of checkpoint_path/ pretrained_weights, when checkpoint_path is not None.
  135. Used when num_classes != checkpoint_num_class. In this case, the module will be initialized with checkpoint_num_class, then weights will be loaded. Finaly
  136. replace_head(new_num_classes=num_classes) is called (useful when wanting to perform transfer learning, from a checkpoint outside of
  137. then ones offered in SG model zoo).
  138. NOTE: Passing pretrained_weights and checkpoint_path is ill-defined and will raise an error.
  139. """
  140. checkpoint_num_classes = checkpoint_num_classes or num_classes
  141. if checkpoint_num_classes:
  142. net = instantiate_model(model_name, arch_params, checkpoint_num_classes, pretrained_weights, download_required_code)
  143. else:
  144. net = instantiate_model(model_name, arch_params, num_classes, pretrained_weights, download_required_code)
  145. if load_backbone and not checkpoint_path:
  146. raise ValueError("Please set checkpoint_path when load_backbone=True")
  147. if checkpoint_path:
  148. load_ema_as_net = "ema_net" in read_ckpt_state_dict(ckpt_path=checkpoint_path).keys()
  149. _ = load_checkpoint_to_model(
  150. ckpt_local_path=checkpoint_path,
  151. load_backbone=load_backbone,
  152. net=net,
  153. strict=strict_load.value if hasattr(strict_load, "value") else strict_load,
  154. load_weights_only=True,
  155. load_ema_as_net=load_ema_as_net,
  156. )
  157. if checkpoint_num_classes != num_classes:
  158. net.replace_head(new_num_classes=num_classes)
  159. return net
Discard
Tip!

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