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

progress_bar.py 6.9 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
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
  1. # Copyright (c) 2017-present, Facebook, Inc.
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the license found in the LICENSE file in
  5. # the root directory of this source tree. An additional grant of patent rights
  6. # can be found in the PATENTS file in the same directory.
  7. """
  8. Wrapper around various loggers and progress bars (e.g., tqdm).
  9. """
  10. from collections import OrderedDict
  11. import json
  12. from numbers import Number
  13. import sys
  14. from tqdm import tqdm
  15. from fairseq.meters import AverageMeter
  16. def build_progress_bar(args, iterator, epoch=None, prefix=None, default='tqdm', no_progress_bar='none'):
  17. if args.log_format is None:
  18. args.log_format = no_progress_bar if args.no_progress_bar else default
  19. if args.log_format == 'tqdm' and not sys.stderr.isatty():
  20. args.log_format = 'simple'
  21. if args.log_format == 'json':
  22. bar = json_progress_bar(iterator, epoch, prefix, args.log_interval)
  23. elif args.log_format == 'none':
  24. bar = noop_progress_bar(iterator, epoch, prefix)
  25. elif args.log_format == 'simple':
  26. bar = simple_progress_bar(iterator, epoch, prefix, args.log_interval)
  27. elif args.log_format == 'tqdm':
  28. bar = tqdm_progress_bar(iterator, epoch, prefix)
  29. else:
  30. raise ValueError('Unknown log format: {}'.format(args.log_format))
  31. return bar
  32. class progress_bar(object):
  33. """Abstract class for progress bars."""
  34. def __init__(self, iterable, epoch=None, prefix=None):
  35. self.iterable = iterable
  36. self.epoch = epoch
  37. self.prefix = ''
  38. if epoch is not None:
  39. self.prefix += '| epoch {:03d}'.format(epoch)
  40. if prefix is not None:
  41. self.prefix += ' | {}'.format(prefix)
  42. def __enter__(self):
  43. return self
  44. def __exit__(self, *exc):
  45. return False
  46. def __iter__(self):
  47. raise NotImplementedError
  48. def log(self, stats):
  49. """Log intermediate stats according to log_interval."""
  50. raise NotImplementedError
  51. def print(self, stats):
  52. """Print end-of-epoch stats."""
  53. raise NotImplementedError
  54. def _str_commas(self, stats):
  55. return ', '.join(key + '=' + stats[key].strip()
  56. for key in stats.keys())
  57. def _str_pipes(self, stats):
  58. return ' | '.join(key + ' ' + stats[key].strip()
  59. for key in stats.keys())
  60. def _format_stats(self, stats):
  61. postfix = OrderedDict(stats)
  62. # Preprocess stats according to datatype
  63. for key in postfix.keys():
  64. # Number: limit the length of the string
  65. if isinstance(postfix[key], Number):
  66. postfix[key] = '{:g}'.format(postfix[key])
  67. # Meter: display both current and average value
  68. elif isinstance(postfix[key], AverageMeter):
  69. postfix[key] = '{:.2f} ({:.2f})'.format(
  70. postfix[key].val, postfix[key].avg)
  71. # Else for any other type, try to get the string conversion
  72. elif not isinstance(postfix[key], str):
  73. postfix[key] = str(postfix[key])
  74. # Else if it's a string, don't need to preprocess anything
  75. return postfix
  76. class json_progress_bar(progress_bar):
  77. """Log output in JSON format."""
  78. def __init__(self, iterable, epoch=None, prefix=None, log_interval=1000):
  79. super().__init__(iterable, epoch, prefix)
  80. self.log_interval = log_interval
  81. self.stats = None
  82. def __iter__(self):
  83. size = float(len(self.iterable))
  84. for i, obj in enumerate(self.iterable):
  85. yield obj
  86. if self.stats is not None and i > 0 and \
  87. self.log_interval is not None and i % self.log_interval == 0:
  88. update = self.epoch - 1 + float(i / size) if self.epoch is not None else None
  89. stats = self._format_stats(self.stats, epoch=self.epoch, update=update)
  90. print(json.dumps(stats), flush=True)
  91. def log(self, stats):
  92. """Log intermediate stats according to log_interval."""
  93. self.stats = stats
  94. def print(self, stats):
  95. """Print end-of-epoch stats."""
  96. self.stats = stats
  97. stats = self._format_stats(self.stats, epoch=self.epoch)
  98. print(json.dumps(stats), flush=True)
  99. def _format_stats(self, stats, epoch=None, update=None):
  100. postfix = OrderedDict()
  101. if epoch is not None:
  102. postfix['epoch'] = epoch
  103. if update is not None:
  104. postfix['update'] = update
  105. # Preprocess stats according to datatype
  106. for key in stats.keys():
  107. # Meter: display both current and average value
  108. if isinstance(stats[key], AverageMeter):
  109. postfix[key] = stats[key].val
  110. postfix[key + '_avg'] = stats[key].avg
  111. else:
  112. postfix[key] = stats[key]
  113. return postfix
  114. class noop_progress_bar(progress_bar):
  115. """No logging."""
  116. def __init__(self, iterable, epoch=None, prefix=None):
  117. super().__init__(iterable, epoch, prefix)
  118. def __iter__(self):
  119. for obj in self.iterable:
  120. yield obj
  121. def log(self, stats):
  122. """Log intermediate stats according to log_interval."""
  123. pass
  124. def print(self, stats):
  125. """Print end-of-epoch stats."""
  126. pass
  127. class simple_progress_bar(progress_bar):
  128. """A minimal logger for non-TTY environments."""
  129. def __init__(self, iterable, epoch=None, prefix=None, log_interval=1000):
  130. super().__init__(iterable, epoch, prefix)
  131. self.log_interval = log_interval
  132. self.stats = None
  133. def __iter__(self):
  134. size = len(self.iterable)
  135. for i, obj in enumerate(self.iterable):
  136. yield obj
  137. if self.stats is not None and i > 0 and \
  138. self.log_interval is not None and i % self.log_interval == 0:
  139. postfix = self._str_commas(self.stats)
  140. print('{}: {:5d} / {:d} {}'.format(self.prefix, i, size, postfix),
  141. flush=True)
  142. def log(self, stats):
  143. """Log intermediate stats according to log_interval."""
  144. self.stats = self._format_stats(stats)
  145. def print(self, stats):
  146. """Print end-of-epoch stats."""
  147. postfix = self._str_pipes(self._format_stats(stats))
  148. print('{} | {}'.format(self.prefix, postfix), flush=True)
  149. class tqdm_progress_bar(progress_bar):
  150. """Log to tqdm."""
  151. def __init__(self, iterable, epoch=None, prefix=None):
  152. super().__init__(iterable, epoch, prefix)
  153. self.tqdm = tqdm(iterable, self.prefix, leave=False)
  154. def __iter__(self):
  155. return iter(self.tqdm)
  156. def log(self, stats):
  157. """Log intermediate stats according to log_interval."""
  158. self.tqdm.set_postfix(self._format_stats(stats), refresh=False)
  159. def print(self, stats):
  160. """Print end-of-epoch stats."""
  161. postfix = self._str_pipes(self._format_stats(stats))
  162. self.tqdm.write('{} | {}'.format(self.tqdm.desc, postfix))
Tip!

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

Comments

Loading...