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.8 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
179
  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. self.s3_location_available = storage_location.startswith('s3')
  34. super().__init__(project_name, experiment_name, storage_location, resumed, training_params, tb_files_user_prompt, launch_tensorboard, tensorboard_port,
  35. self.s3_location_available, self.s3_location_available, self.s3_location_available)
  36. if api_server is not None:
  37. if api_server != os.getenv('WANDB_BASE_URL'):
  38. logger.warning(f'WANDB_BASE_URL environment parameter not set to {api_server}. Setting the parameter')
  39. os.putenv('WANDB_BASE_URL', api_server)
  40. wandb_id = None
  41. if resumed:
  42. wandb_id = self._get_wandb_id()
  43. run = wandb.init(project=project_name, name=experiment_name, entity=entity, resume=resumed, id=wandb_id, **kwargs)
  44. self._set_wandb_id(run.id)
  45. self.save_checkpoints_wandb = save_checkpoints_remote
  46. self.save_tensorboard_wandb = save_tensorboard_remote
  47. self.save_logs_wandb = save_logs_remote
  48. @multi_process_safe
  49. def add_config(self, tag: str, config: dict):
  50. super(WandBSGLogger, self).add_config(tag=tag, config=config)
  51. wandb.config.update(config)
  52. @multi_process_safe
  53. def add_scalar(self, tag: str, scalar_value: float, global_step: int = 0):
  54. super(WandBSGLogger, self).add_scalar(tag=tag, scalar_value=scalar_value, global_step=global_step)
  55. wandb.log(data={tag: scalar_value}, step=global_step)
  56. @multi_process_safe
  57. def add_scalars(self, tag_scalar_dict: dict, global_step: int = 0):
  58. super(WandBSGLogger, self).add_scalars(tag_scalar_dict=tag_scalar_dict, global_step=global_step)
  59. wandb.log(data=tag_scalar_dict, step=global_step)
  60. @multi_process_safe
  61. def add_image(self, tag: str, image: Union[torch.Tensor, np.array, Image.Image], data_format='CHW', global_step: int = 0):
  62. super(WandBSGLogger, self).add_image(tag=tag, image=image, data_format=data_format, global_step=global_step)
  63. if isinstance(image, torch.Tensor):
  64. image = image.cpu().detach().numpy()
  65. if image.shape[0] < 5:
  66. image = image.transpose([1, 2, 0])
  67. wandb.log(data={tag: wandb.Image(image, caption=tag)}, step=global_step)
  68. @multi_process_safe
  69. def add_images(self, tag: str, images: Union[torch.Tensor, np.array], data_format='NCHW', global_step: int = 0):
  70. super(WandBSGLogger, self).add_images(tag=tag, images=images, data_format=data_format, global_step=global_step)
  71. wandb_images = []
  72. for im in images:
  73. if isinstance(im, torch.Tensor):
  74. im = im.cpu().detach().numpy()
  75. if im.shape[0] < 5:
  76. im = im.transpose([1, 2, 0])
  77. wandb_images.append(wandb.Image(im))
  78. wandb.log({tag: wandb_images}, step=global_step)
  79. @multi_process_safe
  80. def add_video(self, tag: str, video: Union[torch.Tensor, np.array], global_step: int = 0):
  81. super().add_video(tag, video, global_step)
  82. if video.ndim > 4:
  83. for index, vid in enumerate(video):
  84. self.add_video(tag=f'{tag}_{index}', video=vid, global_step=global_step)
  85. else:
  86. if isinstance(video, torch.Tensor):
  87. video = video.cpu().detach().numpy()
  88. wandb.log({tag: wandb.Video(video, fps=4)}, step=global_step)
  89. @multi_process_safe
  90. def add_histogram(self, tag: str, values: Union[torch.Tensor, np.array], bins: str, global_step: int = 0):
  91. super().add_histogram(tag, values, bins, global_step)
  92. wandb.log({tag: wandb.Histogram(values, num_bins=bins)}, step=global_step)
  93. @multi_process_safe
  94. def add_text(self, tag: str, text_string: str, global_step: int = 0):
  95. super().add_text(tag, text_string, global_step)
  96. wandb.log({tag: text_string}, step=global_step)
  97. @multi_process_safe
  98. def add_figure(self, tag: str, figure: plt.figure, global_step: int = 0):
  99. super().add_figure(tag, figure, global_step)
  100. wandb.log({tag: figure}, step=global_step)
  101. @multi_process_safe
  102. def close(self):
  103. super().close()
  104. wandb.finish()
  105. @multi_process_safe
  106. def upload(self):
  107. super().upload()
  108. if self.save_tensorboard_wandb:
  109. wandb.save(glob_str=self._get_tensorboard_file_name(), base_path=self._local_dir, policy='now')
  110. if self.save_logs_wandb:
  111. wandb.save(glob_str=self.log_file_path, base_path=self._local_dir, policy='now')
  112. @multi_process_safe
  113. def add_checkpoint(self, tag: str, state_dict: dict, global_step: int = 0):
  114. name = f'ckpt_{global_step}.pth' if tag is None else tag
  115. if not name.endswith('.pth'):
  116. name += '.pth'
  117. path = os.path.join(self._local_dir, name)
  118. torch.save(state_dict, path)
  119. if self.save_checkpoints_wandb:
  120. if self.s3_location_available:
  121. self.model_checkpoints_data_interface.save_remote_checkpoints_file(self.experiment_name, self._local_dir, name)
  122. wandb.save(glob_str=path, base_path=self._local_dir, policy='now')
  123. def _get_tensorboard_file_name(self):
  124. try:
  125. tb_file_path = self.tensorboard_writer.file_writer.event_writer._file_name
  126. except RuntimeError as e:
  127. logger.warning('tensorboard file could not be located for ')
  128. return None
  129. return tb_file_path
  130. def _get_wandb_id(self):
  131. for file in os.listdir(self._local_dir):
  132. if file.startswith(WANDB_ID_PREFIX):
  133. return file.replace(WANDB_ID_PREFIX, '')
  134. def _set_wandb_id(self, id):
  135. for file in os.listdir(self._local_dir):
  136. if file.startswith(WANDB_ID_PREFIX):
  137. os.remove(os.path.join(self._local_dir, file))
  138. os.mknod(os.path.join(self._local_dir, f'{WANDB_ID_PREFIX}{id}'))
  139. def add(self, tag: str, obj: Any, global_step: int = None):
  140. pass
Tip!

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

Comments

Loading...