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

#869 Add DagsHub Logger to Super Gradients

Merged
Ghost merged 1 commits into Deci-AI:master from timho102003:dagshub_logger
@@ -2,5 +2,6 @@ from super_gradients.common.sg_loggers.base_sg_logger import BaseSGLogger
 from super_gradients.common.sg_loggers.clearml_sg_logger import ClearMLSGLogger
 from super_gradients.common.sg_loggers.clearml_sg_logger import ClearMLSGLogger
 from super_gradients.common.sg_loggers.deci_platform_sg_logger import DeciPlatformSGLogger
 from super_gradients.common.sg_loggers.deci_platform_sg_logger import DeciPlatformSGLogger
 from super_gradients.common.sg_loggers.wandb_sg_logger import WandBSGLogger
 from super_gradients.common.sg_loggers.wandb_sg_logger import WandBSGLogger
+from super_gradients.common.sg_loggers.dagshub_sg_logger import DagsHubSGLogger
 
 
-__all__ = ["BaseSGLogger", "ClearMLSGLogger", "DeciPlatformSGLogger", "WandBSGLogger"]
+__all__ = ["BaseSGLogger", "ClearMLSGLogger", "DeciPlatformSGLogger", "WandBSGLogger", "DagsHubSGLogger"]
Discard
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
219
220
221
222
223
224
225
226
227
  1. import os
  2. from pathlib import Path
  3. from typing import Optional
  4. import torch
  5. from super_gradients.common.registry.registry import register_sg_logger
  6. from super_gradients.common.abstractions.abstract_logger import get_logger
  7. from super_gradients.common.sg_loggers.base_sg_logger import BaseSGLogger
  8. from super_gradients.common.environment.ddp_utils import multi_process_safe
  9. logger = get_logger(__name__)
  10. try:
  11. import dagshub
  12. from dagshub.upload import Repo
  13. _import_dagshub_error = None
  14. except (ModuleNotFoundError, ImportError, NameError) as dagshub_import_err:
  15. _import_dagshub_error = dagshub_import_err
  16. try:
  17. import mlflow
  18. _import_mlflow_error = None
  19. except (ModuleNotFoundError, ImportError, NameError) as mlflow_import_err:
  20. _import_mlflow_error = mlflow_import_err
  21. @register_sg_logger("dagshub_sg_logger")
  22. class DagsHubSGLogger(BaseSGLogger):
  23. def __init__(
  24. self,
  25. project_name: str,
  26. experiment_name: str,
  27. storage_location: str,
  28. resumed: bool,
  29. training_params: dict,
  30. checkpoints_dir_path: str,
  31. tb_files_user_prompt: bool = False,
  32. launch_tensorboard: bool = False,
  33. tensorboard_port: int = None,
  34. save_checkpoints_remote: bool = True,
  35. save_tensorboard_remote: bool = True,
  36. save_logs_remote: bool = True,
  37. monitor_system: bool = None,
  38. dagshub_repository: Optional[str] = None,
  39. log_mlflow_only: bool = False,
  40. ):
  41. """
  42. :param experiment_name: Name used for logging and loading purposes
  43. :param storage_location: If set to 's3' (i.e. s3://my-bucket) saves the Checkpoints in AWS S3 otherwise saves the Checkpoints Locally
  44. :param resumed: If true, then old tensorboard files will **NOT** be deleted when tb_files_user_prompt=True
  45. :param training_params: training_params for the experiment.
  46. :param checkpoints_dir_path: Local root directory path where all experiment logging directories will reside.
  47. :param tb_files_user_prompt: Asks user for Tensorboard deletion prompt.
  48. :param launch_tensorboard: Whether to launch a TensorBoard process.
  49. :param tensorboard_port: Specific port number for the tensorboard to use when launched (when set to None,
  50. some free port number will be used
  51. :param save_checkpoints_remote: Saves checkpoints in s3 and DagsHub.
  52. :param save_tensorboard_remote: Saves tensorboard in s3.
  53. :param save_logs_remote: Saves log files in s3 and DagsHub.
  54. :param monitor_system: Save the system statistics (GPU utilization, CPU, ...) in the tensorboard
  55. :param dagshub_repository: Format: <dagshub_username>/<dagshub_reponame> format is set correctly to avoid
  56. any potential issues. If you are utilizing the dagshub_sg_logger, please specify
  57. the dagshub_repository in sg_logger_params to prevent any interruptions from
  58. prompts during automated pipelines. In the event that the repository does not
  59. exist, it will be created automatically on your behalf.
  60. :param log_mlflow_only: Skip logging to DVC, use MLflow for all artifacts being logged
  61. """
  62. if monitor_system is not None:
  63. logger.warning("monitor_system not available on DagsHubSGLogger. To remove this warning, please don't set monitor_system in your logger parameters")
  64. self.s3_location_available = storage_location.startswith("s3")
  65. super().__init__(
  66. project_name=project_name,
  67. experiment_name=experiment_name,
  68. storage_location=storage_location,
  69. resumed=resumed,
  70. training_params=training_params,
  71. checkpoints_dir_path=checkpoints_dir_path,
  72. tb_files_user_prompt=tb_files_user_prompt,
  73. launch_tensorboard=launch_tensorboard,
  74. tensorboard_port=tensorboard_port,
  75. save_checkpoints_remote=self.s3_location_available,
  76. save_tensorboard_remote=self.s3_location_available,
  77. save_logs_remote=self.s3_location_available,
  78. monitor_system=False,
  79. )
  80. if _import_dagshub_error:
  81. raise _import_dagshub_error
  82. if _import_mlflow_error:
  83. raise _import_mlflow_error
  84. self.repo_name, self.repo_owner, self.remote = None, None, None
  85. if dagshub_repository:
  86. self.repo_name, self.repo_owner = self.splitter(dagshub_repository)
  87. dagshub_auth = os.getenv("DAGSHUB_USER_TOKEN")
  88. if dagshub_auth:
  89. dagshub.auth.add_app_token(dagshub_auth)
  90. self._init_env_dependency()
  91. self.log_mlflow_only = log_mlflow_only
  92. self.save_checkpoints_dagshub = save_checkpoints_remote
  93. self.save_logs_dagshub = save_logs_remote
  94. @staticmethod
  95. def splitter(repo):
  96. splitted = repo.split("/")
  97. if len(splitted) != 2:
  98. raise ValueError(f"Invalid input, should be owner_name/repo_name, but got {repo} instead")
  99. return splitted[1], splitted[0]
  100. def _init_env_dependency(self):
  101. """
  102. The function creates paths for the DVC directory, models, and artifacts, obtains an authentication token from
  103. Dagshub, and sets MLflow tracking credentials. It also checks whether the repository name and owner have been
  104. set and prompts the user to enter them if they haven't. If the remote URI is not set or does not include
  105. "dagshub", Dagshub is initialized with the repository name and owner, and the remote URI is obtained. The method
  106. then creates a Repo object with the repository information and sets the DVC folder to the DVC directory path.
  107. """
  108. self.paths = {
  109. "dvc_directory": Path("artifacts"),
  110. "models": Path("models"),
  111. "artifacts": Path("artifacts"),
  112. }
  113. token = dagshub.auth.get_token()
  114. os.environ["MLFLOW_TRACKING_USERNAME"] = token
  115. os.environ["MLFLOW_TRACKING_PASSWORD"] = token
  116. # Check mlflow environment variable is set:
  117. if not self.repo_name or not self.repo_owner:
  118. self.repo_name, self.repo_owner = self.splitter(input("Please insert your repository owner_name/repo_name:"))
  119. if not self.remote or "dagshub" not in os.getenv("MLFLOW_TRACKING_URI"):
  120. dagshub.init(repo_name=self.repo_name, repo_owner=self.repo_owner)
  121. self.remote = os.getenv("MLFLOW_TRACKING_URI")
  122. self.repo = Repo(
  123. owner=self.remote.split(os.sep)[-2],
  124. name=self.remote.split(os.sep)[-1].replace(".mlflow", ""),
  125. branch=os.getenv("BRANCH", "main"),
  126. )
  127. self.dvc_folder = self.repo.directory(str(self.paths["dvc_directory"]))
  128. mlflow.set_tracking_uri(self.remote)
  129. mlflow.set_experiment(self.experiment_name)
  130. self.run = mlflow.start_run(nested=True)
  131. return self.run
  132. @multi_process_safe
  133. def _dvc_add(self, local_path="", remote_path=""):
  134. if not os.path.isfile(local_path):
  135. FileExistsError(f"Invalid file path: {local_path}")
  136. self.dvc_folder.add(file=local_path, path=remote_path)
  137. @multi_process_safe
  138. def _dvc_commit(self, commit=""):
  139. self.dvc_folder.commit(commit, versioning="dvc", force=True)
  140. @multi_process_safe
  141. def add_config(self, tag: str, config: dict):
  142. super(DagsHubSGLogger, self).add_config(tag=tag, config=config)
  143. param_keys = config.keys()
  144. for pk in param_keys:
  145. for k, v in config[pk].items():
  146. try:
  147. mlflow.log_params({k: v})
  148. except Exception:
  149. logger.warning(f"Skip to log {k}: {v}")
  150. @multi_process_safe
  151. def add_scalar(self, tag: str, scalar_value: float, global_step: int = 0):
  152. super(DagsHubSGLogger, self).add_scalar(tag=tag, scalar_value=scalar_value, global_step=global_step)
  153. mlflow.log_metric(key=tag, value=scalar_value, step=global_step)
  154. @multi_process_safe
  155. def add_scalars(self, tag_scalar_dict: dict, global_step: int = 0):
  156. super(DagsHubSGLogger, self).add_scalars(tag_scalar_dict=tag_scalar_dict, global_step=global_step)
  157. mlflow.log_metrics(metrics=tag_scalar_dict, step=global_step)
  158. @multi_process_safe
  159. def close(self):
  160. super().close()
  161. try:
  162. if not self.log_mlflow_only:
  163. self._dvc_commit(commit=f"Adding all artifacts from run {mlflow.active_run().info.run_id}")
  164. mlflow.end_run()
  165. except Exception:
  166. pass
  167. @multi_process_safe
  168. def add_file(self, file_name: str = None):
  169. super().add_file(file_name)
  170. if self.log_mlflow_only:
  171. mlflow.log_artifact(file_name)
  172. else:
  173. self._dvc_add(local_path=file_name, remote_path=os.path.join(self.paths["artifacts"], self.experiment_log_path))
  174. @multi_process_safe
  175. def upload(self):
  176. super().upload()
  177. if self.save_logs_dagshub:
  178. if self.log_mlflow_only:
  179. mlflow.log_artifact(self.experiment_log_path)
  180. else:
  181. self._dvc_add(local_path=self.experiment_log_path, remote_path=os.path.join(self.paths["artifacts"], self.experiment_log_path))
  182. @multi_process_safe
  183. def add_checkpoint(self, tag: str, state_dict: dict, global_step: int = 0):
  184. name = f"ckpt_{global_step}.pth" if tag is None else tag
  185. if not name.endswith(".pth"):
  186. name += ".pth"
  187. path = os.path.join(self._local_dir, name)
  188. torch.save(state_dict, path)
  189. if self.save_checkpoints_dagshub:
  190. mlflow.log_artifact(path)
  191. if (global_step >= (self.max_global_steps - 1)) and not self.log_mlflow_only:
  192. self._dvc_add(local_path=path, remote_path=os.path.join(self.paths["models"], name))
Discard