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

wandb_sg_logger.py 7.6 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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
  1. import os
  2. from typing import Union, Optional, Any
  3. import numpy as np
  4. from PIL import Image
  5. import matplotlib.pyplot as plt
  6. import torch
  7. from super_gradients.common.abstractions.abstract_logger import get_logger
  8. from super_gradients.common.sg_loggers.base_sg_logger import BaseSGLogger
  9. from super_gradients.common.environment.env_helpers import multi_process_safe
  10. logger = get_logger(__name__)
  11. try:
  12. import wandb
  13. except (ModuleNotFoundError, ImportError, NameError):
  14. pass # no action or logging - this is normal in most cases
  15. WANDB_ID_PREFIX = 'wandb_id.'
  16. class WandBSGLogger(BaseSGLogger):
  17. def __init__(self, project_name: str, experiment_name: str, storage_location: str, resumed: bool, training_params: dict, tb_files_user_prompt: bool = False,
  18. launch_tensorboard: bool = False, tensorboard_port: int = None, save_checkpoints_remote: bool = True, save_tensorboard_remote: bool = True,
  19. save_logs_remote: bool = True, entity: Optional[str] = None, api_server: Optional[str] = None, **kwargs):
  20. """
  21. :param experiment_name: Used for logging and loading purposes
  22. :param s3_path: If set to 's3' (i.e. s3://my-bucket) saves the Checkpoints in AWS S3 otherwise saves the Checkpoints Locally
  23. :param checkpoint_loaded: if true, then old tensorboard files will *not* be deleted when tb_files_user_prompt=True
  24. :param max_epochs: the number of epochs planned for this training
  25. :param tb_files_user_prompt: Asks user for Tensorboard deletion prompt.
  26. :param launch_tensorboard: Whether to launch a TensorBoard process.
  27. :param tensorboard_port: Specific port number for the tensorboard to use when launched (when set to None, some free port
  28. number will be used
  29. :param save_checkpoints_remote: Saves checkpoints in s3.
  30. :param save_tensorboard_remote: Saves tensorboard in s3.
  31. :param save_logs_remote: Saves log files in s3.
  32. """
  33. super().__init__(project_name, experiment_name, storage_location, resumed, training_params, tb_files_user_prompt, launch_tensorboard, tensorboard_port,
  34. save_checkpoints_remote, save_tensorboard_remote, save_logs_remote)
  35. if api_server is not None:
  36. if api_server != os.getenv('WANDB_BASE_URL'):
  37. logger.warning(f'WANDB_BASE_URL environment parameter not set to {api_server}. Setting the parameter')
  38. os.putenv('WANDB_BASE_URL', api_server)
  39. wandb_id = None
  40. if resumed:
  41. wandb_id = self._get_wandb_id()
  42. run = wandb.init(project=project_name, name=experiment_name, entity=entity, resume=resumed, id=wandb_id, **kwargs)
  43. self._set_wandb_id(run.id)
  44. self.save_checkpoints_wandb = save_checkpoints_remote
  45. self.save_tensorboard_wandb = save_tensorboard_remote
  46. self.save_logs_wandb = save_logs_remote
  47. @multi_process_safe
  48. def add_config(self, tag: str, config: dict):
  49. super(WandBSGLogger, self).add_config(tag=tag, config=config)
  50. wandb.config.update(config)
  51. @multi_process_safe
  52. def add_scalar(self, tag: str, scalar_value: float, global_step: int = 0):
  53. super(WandBSGLogger, self).add_scalar(tag=tag, scalar_value=scalar_value, global_step=global_step)
  54. wandb.log(data={tag: scalar_value}, step=global_step)
  55. @multi_process_safe
  56. def add_scalars(self, tag_scalar_dict: dict, global_step: int = 0):
  57. super(WandBSGLogger, self).add_scalars(tag_scalar_dict=tag_scalar_dict, global_step=global_step)
  58. wandb.log(data=tag_scalar_dict, step=global_step)
  59. @multi_process_safe
  60. def add_image(self, tag: str, image: Union[torch.Tensor, np.array, Image.Image], data_format='CHW', global_step: int = 0):
  61. super(WandBSGLogger, self).add_image(tag=tag, image=image, data_format=data_format, global_step=global_step)
  62. if isinstance(image, torch.Tensor):
  63. image = image.cpu().detach().numpy()
  64. if image.shape[0] < 5:
  65. image = image.transpose([1, 2, 0])
  66. wandb.log(data={tag: wandb.Image(image, caption=tag)}, step=global_step)
  67. @multi_process_safe
  68. def add_images(self, tag: str, images: Union[torch.Tensor, np.array], data_format='NCHW', global_step: int = 0):
  69. super(WandBSGLogger, self).add_images(tag=tag, images=images, data_format=data_format, global_step=global_step)
  70. wandb_images = []
  71. for im in images:
  72. if isinstance(im, torch.Tensor):
  73. im = im.cpu().detach().numpy()
  74. if im.shape[0] < 5:
  75. im = im.transpose([1, 2, 0])
  76. wandb_images.append(wandb.Image(im))
  77. wandb.log({tag: wandb_images}, step=global_step)
  78. @multi_process_safe
  79. def add_video(self, tag: str, video: Union[torch.Tensor, np.array], global_step: int = 0):
  80. super().add_video(tag, video, global_step)
  81. if video.ndim > 4:
  82. for index, vid in enumerate(video):
  83. self.add_video(tag=f'{tag}_{index}', video=vid, global_step=global_step)
  84. else:
  85. if isinstance(video, torch.Tensor):
  86. video = video.cpu().detach().numpy()
  87. wandb.log({tag: wandb.Video(video, fps=4)}, step=global_step)
  88. @multi_process_safe
  89. def add_histogram(self, tag: str, values: Union[torch.Tensor, np.array], bins: str, global_step: int = 0):
  90. super().add_histogram(tag, values, bins, global_step)
  91. wandb.log({tag: wandb.Histogram(values, num_bins=bins)}, step=global_step)
  92. @multi_process_safe
  93. def add_text(self, tag: str, text_string: str, global_step: int = 0):
  94. super().add_text(tag, text_string, global_step)
  95. wandb.log({tag: text_string}, step=global_step)
  96. @multi_process_safe
  97. def add_figure(self, tag: str, figure: plt.figure, global_step: int = 0):
  98. super().add_figure(tag, figure, global_step)
  99. wandb.log({tag: figure}, step=global_step)
  100. @multi_process_safe
  101. def close(self):
  102. super().close()
  103. wandb.finish()
  104. @multi_process_safe
  105. def upload(self):
  106. super().upload()
  107. if self.save_tensorboard_wandb:
  108. wandb.save(glob_str=self._get_tensorboard_file_name(), base_path=self._local_dir, policy='now')
  109. if self.save_logs_wandb:
  110. wandb.save(glob_str=self.log_file_path, base_path=self._local_dir, policy='now')
  111. @multi_process_safe
  112. def add_checkpoint(self, tag: str, state_dict: dict, global_step: int = 0):
  113. name = f'ckpt_{global_step}.pth' if tag is None else tag
  114. if not name.endswith('.pth'):
  115. name += '.pth'
  116. path = os.path.join(self._local_dir, name)
  117. torch.save(state_dict, path)
  118. if self.save_checkpoints_wandb:
  119. self.model_checkpoints_data_interface.save_remote_checkpoints_file(self.experiment_name, self._local_dir, name)
  120. wandb.save(glob_str=path, base_path=self._local_dir, policy='now')
  121. def _get_tensorboard_file_name(self):
  122. try:
  123. tb_file_path = self.tensorboard_writer.file_writer.event_writer._file_name
  124. except RuntimeError as e:
  125. logger.warning('tensorboard file could not be located for ')
  126. return None
  127. return tb_file_path
  128. def _get_wandb_id(self):
  129. for file in os.listdir(self._local_dir):
  130. if file.startswith(WANDB_ID_PREFIX):
  131. return file.replace(WANDB_ID_PREFIX, '')
  132. def _set_wandb_id(self, id):
  133. for file in os.listdir(self._local_dir):
  134. if file.startswith(WANDB_ID_PREFIX):
  135. os.remove(os.path.join(self._local_dir, file))
  136. os.mknod(os.path.join(self._local_dir, f'{WANDB_ID_PREFIX}{id}'))
  137. def add(self, tag: str, obj: Any, global_step: int = None):
  138. pass
Tip!

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

Comments

Loading...