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

#683 Bugfix/INFRA-1707_fixing-docker-publish

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

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