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
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
  1. import os
  2. import sys
  3. from datetime import datetime
  4. from pathlib import Path
  5. from io import StringIO
  6. import atexit
  7. from threading import Lock
  8. from super_gradients.common.environment.ddp_utils import multi_process_safe, is_main_process
  9. class BufferWriter:
  10. """File writer buffer that opens a file only when flushing and under the condition that threshold buffersize was reached."""
  11. FILE_BUFFER_SIZE = 10_000 # Number of chars to be buffered before writing the buffer on disk.
  12. def __init__(self, filename: str, buffer: StringIO, buffer_size: int, lock: Lock):
  13. """
  14. :param filename: Name of the file where to write the bugger
  15. :param buffer: Buffer object
  16. :param buffer_size: Number of chars to be buffered before writing the buffer on disk.
  17. :param lock: Thread lock to prevent multiple threads to write at the same time
  18. """
  19. self.buffer = buffer
  20. self.filename = filename
  21. self.buffer_size = buffer_size
  22. self.lock = lock
  23. def write(self, data: str):
  24. """Write to buffer (not on disk)."""
  25. with self.lock:
  26. self.buffer.write(data)
  27. if self._require_flush():
  28. self.flush()
  29. def flush(self, force: bool = False):
  30. """Write the buffer on disk if relevant."""
  31. if force or self._require_flush():
  32. with self.lock:
  33. os.makedirs(os.path.dirname(self.filename), exist_ok=True)
  34. with open(self.filename, "a", encoding="utf-8") as f:
  35. f.write(self.buffer.getvalue())
  36. self.buffer.truncate(0)
  37. self.buffer.seek(0)
  38. def _require_flush(self) -> bool:
  39. """Indicate if a buffer is needed (i.e. if buffer size above threshold)"""
  40. return len(self.buffer.getvalue()) > self.buffer_size
  41. class StderrTee(BufferWriter):
  42. """Duplicate the stderr stream to save it into a given file."""
  43. def __init__(self, filename: str, buffer: StringIO, buffer_size: int, lock: Lock):
  44. """
  45. :param filename: Name of the file where to write the bugger
  46. :param buffer: Buffer object
  47. :param buffer_size: Number of chars to be buffered before writing the buffer on disk.
  48. :param lock: Thread lock to prevent multiple threads to write at the same time
  49. """
  50. super().__init__(filename, buffer, buffer_size, lock)
  51. self.stderr = sys.stderr
  52. sys.stderr = self
  53. def __del__(self):
  54. sys.stderr = self.stderr
  55. def write(self, data):
  56. super().write(data)
  57. self.stderr.write(data)
  58. def __getattr__(self, attr):
  59. return getattr(self.stderr, attr)
  60. class StdoutTee(BufferWriter):
  61. """Duplicate the stdout stream to save it into a given file."""
  62. def __init__(self, filename: str, buffer, buffer_size: int, lock: Lock):
  63. """
  64. :param filename: Name of the file where to write the bugger
  65. :param buffer: Buffer object
  66. :param buffer_size: Number of chars to be buffered before writing the buffer on disk.
  67. :param lock: Thread lock to prevent multiple threads to write at the same time
  68. """
  69. super().__init__(filename, buffer, buffer_size, lock)
  70. self.stdout = sys.stdout
  71. sys.stdout = self
  72. def __del__(self):
  73. sys.stdout = self.stdout
  74. def write(self, data):
  75. super().write(data)
  76. self.stdout.write(data)
  77. def __getattr__(self, attr):
  78. return getattr(self.stdout, attr)
  79. def copy_file(src_filename: str, dest_filename: str, copy_mode: str = "w"):
  80. """Copy a file from source to destination. Also works when the destination folder does not exist."""
  81. os.makedirs(os.path.dirname(dest_filename), exist_ok=True)
  82. if os.path.exists(src_filename):
  83. with open(src_filename, "r", encoding="utf-8") as src:
  84. with open(dest_filename, copy_mode, encoding="utf-8") as dst:
  85. dst.write(src.read())
  86. class ConsoleSink:
  87. """Singleton responsible to sink the console streams (stdout/stderr) into a file."""
  88. def __init__(self):
  89. self._setup()
  90. atexit.register(self._flush) # Flush at the end of the process
  91. @multi_process_safe
  92. def _setup(self):
  93. """On instantiation, setup the default sink file."""
  94. filename = Path.home() / "sg_logs" / "console.log"
  95. filename.parent.mkdir(exist_ok=True)
  96. self.filename = str(filename)
  97. os.makedirs(os.path.dirname(self.filename), exist_ok=True)
  98. buffer = StringIO()
  99. lock = Lock()
  100. self.stdout = StdoutTee(filename=self.filename, buffer=buffer, buffer_size=BufferWriter.FILE_BUFFER_SIZE, lock=lock)
  101. self.stderr = StderrTee(filename=self.filename, buffer=buffer, buffer_size=BufferWriter.FILE_BUFFER_SIZE, lock=lock)
  102. # We don't want to rewrite this for subprocesses when using DDP.
  103. if is_main_process():
  104. with open(self.filename, mode="w", encoding="utf-8") as f:
  105. f.write("============================================================\n")
  106. f.write(f'New run started at {datetime.now().strftime("%Y-%m-%d.%H:%M:%S.%f")}\n')
  107. f.write(f'sys.argv: "{" ".join(sys.argv)}"\n')
  108. f.write("============================================================\n")
  109. self.stdout.write(f"The console stream is logged into {self.filename}\n")
  110. @multi_process_safe
  111. def _set_location(self, filename: str):
  112. """Copy and redirect the sink file into another location."""
  113. self._flush()
  114. prev_filename = self.filename
  115. copy_file(src_filename=prev_filename, dest_filename=filename, copy_mode="a")
  116. self.filename = filename
  117. self.stdout.filename = filename
  118. self.stderr.filename = filename
  119. self.stdout.write(f"The console stream is now moved to {filename}\n")
  120. @staticmethod
  121. def set_location(filename: str) -> None:
  122. """Copy and redirect the sink file into another location."""
  123. _console_sink._set_location(filename)
  124. @multi_process_safe
  125. def _flush(self):
  126. """Force the flush on stdout and stderr."""
  127. self.stdout.flush(force=True)
  128. self.stderr.flush(force=True)
  129. @staticmethod
  130. def flush():
  131. """Force the flush on stdout and stderr."""
  132. _console_sink._flush()
  133. @staticmethod
  134. def get_filename():
  135. """Get the filename of the sink."""
  136. return _console_sink.filename
  137. _console_sink = ConsoleSink()
Discard
Tip!

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