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

#643 PPYolo-E

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:feature/SG-344-PP-Yolo-E-Training-Replicate-Recipe
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
  1. import os
  2. import json
  3. import sys
  4. from zipfile import ZipFile
  5. from typing import List, Optional, Any
  6. from pathlib import Path
  7. import hydra
  8. import importlib.util
  9. from hydra.core.global_hydra import GlobalHydra
  10. from omegaconf import DictConfig
  11. from torch import nn
  12. import super_gradients
  13. from super_gradients.common.environment.env_variables import env_variables
  14. from super_gradients.common.abstractions.abstract_logger import get_logger
  15. logger = get_logger(__name__)
  16. client_enabled = True
  17. try:
  18. from deci_lab_client.client import DeciPlatformClient
  19. from deci_lab_client.types import S3SignedUrl
  20. from deci_lab_client.models import ModelBenchmarkState
  21. from deci_common.data_interfaces.files_data_interface import FilesDataInterface
  22. from deci_lab_client.models import AutoNACFileName
  23. from deci_lab_client import ApiException
  24. except (ImportError, NameError):
  25. client_enabled = False
  26. class DeciClient:
  27. """
  28. A client to deci platform and model zoo.
  29. requires credentials for connection
  30. """
  31. def __init__(self):
  32. if not client_enabled:
  33. logger.error(
  34. "deci-lab-client or deci-common are not installed. Model cannot be loaded from deci lab."
  35. "Please install deci-lab-client>=2.55.0 and deci-common>=3.4.1"
  36. )
  37. return
  38. self.api_host = env_variables.DECI_API_HOST
  39. self.lab_client = DeciPlatformClient(api_host=self.api_host)
  40. self.lab_client.login(token=env_variables.DECI_PLATFORM_TOKEN)
  41. def _get_file(self, model_name: str, file_name: str) -> Optional[str]:
  42. """Get a file from the DeciPlatform if it exists, otherwise returns None
  43. :param model_name: Name of the model to download from, as saved in the platform.
  44. :param file_name: Name of the file to download
  45. :return: Path were the downloaded file was saved to. None if not found.
  46. """
  47. try:
  48. response = self.lab_client.get_autonac_model_file_link(
  49. model_name=model_name, file_name=file_name, super_gradients_version=super_gradients.__version__
  50. )
  51. download_link = response.data
  52. except ApiException as e:
  53. if e.status == 401:
  54. logger.error(
  55. "Unauthorized. wrong token or token was not defined. please login to deci-lab-client " "by calling DeciPlatformClient().login(<token>)"
  56. )
  57. elif e.status == 400 and e.body is not None and "message" in e.body:
  58. logger.error(f"Deci client: {json.loads(e.body)['message']}")
  59. else:
  60. logger.debug(e.body)
  61. return None
  62. return FilesDataInterface.download_temporary_file(file_url=download_link)
  63. def get_model_arch_params(self, model_name: str) -> Optional[DictConfig]:
  64. """Get the model arch_params from DeciPlatform.
  65. :param model_name: Name of the model as saved in the platform.
  66. :return: arch_params. None if arch_params were not found for this specific model on this SG version."""
  67. arch_params_file = self._get_file(model_name, AutoNACFileName.STRUCTURE_YAML)
  68. if arch_params_file is None:
  69. return None
  70. return _load_cfg(config_path=arch_params_file)
  71. def get_model_recipe(self, model_name: str) -> Optional[DictConfig]:
  72. """Get the model recipe from DeciPlatform.
  73. :param model_name: Name of the model as saved in the platform.
  74. :return: recipe. None if recipe were not found for this specific model on this SG version."""
  75. recipe_file = self._get_file(model_name, AutoNACFileName.RECIPE_YAML)
  76. if recipe_file is None:
  77. return None
  78. return _load_cfg(config_path=recipe_file)
  79. def get_model_weights(self, model_name: str) -> Optional[str]:
  80. """Get the path to model weights (downloaded locally).
  81. :param model_name: Name of the model as saved in the platform.
  82. :return: model_weights path. None if weights were not found for this specific model on this SG version."""
  83. return self._get_file(model_name=model_name, file_name=AutoNACFileName.WEIGHTS_PTH)
  84. def download_and_load_model_additional_code(self, model_name: str, target_path: str, package_name: str = "deci_model_code") -> None:
  85. """
  86. try to download code files for this model.
  87. if found, code files will be placed in the target_path/package_name and imported dynamically
  88. """
  89. file = self._get_file(model_name=model_name, file_name=AutoNACFileName.CODE_ZIP)
  90. package_path = os.path.join(target_path, package_name)
  91. if file is not None:
  92. # crete the directory
  93. os.makedirs(package_path, exist_ok=True)
  94. # extract code files
  95. with ZipFile(file) as zipfile:
  96. zipfile.extractall(package_path)
  97. # add an init file that imports all code files
  98. with open(os.path.join(package_path, "__init__.py"), "w") as init_file:
  99. all_str = "\n\n__all__ = ["
  100. for code_file in os.listdir(path=package_path):
  101. if code_file.endswith(".py") and not code_file.startswith("__init__"):
  102. init_file.write(f'import {code_file.replace(".py", "")}\n')
  103. all_str += f'"{code_file.replace(".py", "")}", '
  104. all_str += "]\n\n"
  105. init_file.write(all_str)
  106. # include in path and import
  107. sys.path.insert(1, package_path)
  108. importlib.import_module(package_name)
  109. logger.info(
  110. f"*** IMPORTANT ***: files required for the model {model_name} were downloaded and added to your code in:\n{package_path}\n"
  111. f"These files will be downloaded to the same location each time the model is fetched from the deci-client.\n"
  112. f"you can override this by passing models.get(... download_required_code=False) and importing the files yourself"
  113. )
  114. def upload_model(self, model: nn.Module, model_meta_data, optimization_request_form):
  115. """
  116. This function will upload the trained model to the Deci Lab
  117. Args:
  118. model: The resulting model from the training process
  119. model_meta_data: Metadata to accompany the model
  120. optimization_request_form: The optimization parameters
  121. """
  122. self.lab_client.add_model(
  123. add_model_request=model_meta_data,
  124. optimization_request=optimization_request_form,
  125. local_loaded_model=model,
  126. )
  127. def is_model_benchmarking(self, name: str) -> bool:
  128. """Check if a given model is still benchmarking or not.
  129. :param name: The mode name.
  130. """
  131. benchmark_state = self.lab_client.get_model_by_name(name=name).data.benchmark_state
  132. return benchmark_state in [ModelBenchmarkState.IN_PROGRESS, ModelBenchmarkState.PENDING]
  133. def register_experiment(self, name: str, model_name: str):
  134. """Registers a training experiment in Deci's backend.
  135. :param name: Name of the experiment to register
  136. :param model_name: Name of the model architecture to connect the experiment to
  137. """
  138. self.lab_client.register_experiment(name=name, model_name=model_name)
  139. def save_experiment_file(self, file_path: str):
  140. """
  141. Uploads a training related file to Deci's location in S3. This can be a TensorBoard file or a log
  142. :params file_path: The local path of the file to be uploaded
  143. """
  144. self.lab_client.save_experiment_file(file_path=file_path)
  145. def upload_file_to_s3(self, tag: str, level: str, from_path: str):
  146. """Upload a file to the platform S3 bucket.
  147. :param tag: Tag that will be associated to the file.
  148. :param level: Logging level that will be used to notify the monitoring system that the file was uploaded.
  149. :param from_path: Path of the file to upload.
  150. """
  151. data = self.lab_client.upload_log_url(tag=tag, level=level)
  152. signed_url = S3SignedUrl(**data.data)
  153. self.lab_client.upload_file_to_s3(from_path=from_path, s3_signed_url=signed_url)
  154. def add_model(
  155. self,
  156. model_metadata,
  157. hardware_types: List[str],
  158. model_path: Optional[str] = None,
  159. model: Optional[nn.Module] = None,
  160. **kwargs: Any,
  161. ):
  162. """Adds a new model to the company's model repository.
  163. :param model_metadata: The model metadata.
  164. :param hardware_types: The hardware types you want to benchmark the model on.
  165. :param model_path: The path of the model on the local operating system.
  166. :param model: Pytorch loaded model object.
  167. If your model's framework is pytorch you may pass the following parameters as kwargs in order to control the conversion to onnx
  168. :param kwargs: Extra arguments to be passed to the PyTorch to ONNX conversion, for example:
  169. opset_version
  170. do_constant_folding
  171. dynamic_axes
  172. input_names
  173. output_names
  174. """
  175. self.lab_client.add_model_v2(model_metadata=model_metadata, hardware_types=hardware_types, model_path=model_path, model=model, **kwargs)
  176. def _load_cfg(config_path: str) -> DictConfig:
  177. """Load a hydra config file.
  178. :param config_path: Full path of the hydra config file.
  179. :return: Hydra config instance"""
  180. GlobalHydra.instance().clear()
  181. arch_params_file = Path(config_path)
  182. with hydra.initialize_config_dir(config_dir=str(arch_params_file.parent), version_base=None):
  183. return hydra.compose(config_name=arch_params_file.name)
Discard
Tip!

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