File size: 10,371 Bytes
957e2dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import torch
import torch.nn as nn
from copy import deepcopy
import contextlib
import math
import time
import logging
import sys
import json

from typing import Union, Dict, Any

from pathlib import Path

from torch.utils.tensorboard import SummaryWriter

from src.constants import RUNS_DIR
from src.utils.filesystem import ensure_dir
from src.utils.plotting import *

################################################################################
# Logging utility with optional TensorBoard support
################################################################################


class Writer:
    """

    Handles file, console, and TensorBoard logging

    """
    def __init__(self,

                 root_dir: Union[str, Path] = RUNS_DIR,

                 name: str = None,

                 use_tb: bool = False,

                 log_iter: int = 100,

                 use_timestamp: bool = True,

                 log_images: bool = False,

                 **kwargs

                 ):
        """

        Configure logging.



        :param root_dir: root logging directory

        :param name: descriptive name for run

        :param use_tb: if True, use TensorBoard

        :param log_iter: iterations between logging

        """

        # generate run-specific name and create directory
        run_name = f'{name}'
        if use_timestamp:
            run_name += f'_{time.strftime("%m-%d-%H_%M_%S")}'
        self.run_dir = Path(root_dir) / run_name
        ensure_dir(self.run_dir)

        # prepare checkpoint directory
        self.checkpoint_dir = self.run_dir / 'checkpoints'

        # log to TensorBoard
        self.use_tb = use_tb
        self.log_iter = log_iter
        self.writer = SummaryWriter(
            log_dir=str(self.run_dir),
            flush_secs=20,
        ) if self.use_tb else None

        # log to console and file 'log.txt'
        self.logger = logging.getLogger(run_name)

        self.logger.setLevel(logging.INFO)
        self.logger.addHandler(
            logging.StreamHandler(sys.stdout)
        )
        self.logger.addHandler(
            logging.FileHandler(self.run_dir / 'log.txt')
        )

        # to avoid segmentation faults, it may be necessary to skip image
        # logging
        self.log_images = log_images

        # self.logger.info(f'Logging to {self.run_dir}')

        # disable Matplotlib logging
        logging.getLogger('matplotlib.font_manager').disabled = True

    def get_run_dir(self):
        return str(self.run_dir)

    def log_info(self, info: str):
        """

        Log generic statements

        """
        self.logger.info(info)

    def _dict_to_str(self, d: dict):
        """Recursively cast dictionary entries to strings"""

        d_out = {}

        for k, v in d.items():
            if isinstance(v, dict):
                d_out[k] = self._dict_to_str(v)
            elif not isinstance(v, (float, int, bool)):
                d_out[k] = str(v)
            else:
                d_out[k] = v
        return d_out

    def log_config(self,

                   config: Union[dict, str],

                   tag: str = "config",

                   path: Union[str, Path] = None):
        """Save config file for run, given dictionary"""

        path = path if path is not None else self.run_dir / f'{tag}.conf'

        with open(path, "w") as out_config:
            self.logger.info(f'Saving config to {path}')

            if isinstance(config, dict):
                config = self._dict_to_str(config)
                json.dump(config, out_config, indent=4)
            else:
                out_config.write(config)

    def log_scalar(self, x: torch.Tensor, tag: str, global_step: int = 0):
        """

        Log scalar

        """

        # only log at specified iterations
        if not self.log_iter or global_step % self.log_iter:
            return

        # log scalar to file and console
        self.logger.info(f'iter {global_step}\t{tag}: {x}')

        # if TensorBoard is enabled
        if self.use_tb:
            self.writer.add_scalar(f'{tag}', x, global_step=global_step)
            self.writer.flush()

    def log_logits(self,

                   x: torch.Tensor,

                   target: int = None,

                   tag: str = None,

                   global_step: int = 0):
        """

        Log class scores (logits)

        """

        # only log at specified iterations
        if not self.log_iter or global_step % self.log_iter:
            return

        # log plot to TensorBoard
        if self.use_tb and self.log_images:
            self.writer.add_image(
                f"{tag}", plot_logits(x, target),
                global_step=global_step
            )

            self.writer.flush()

    def log_audio(self,

                  x: torch.Tensor,

                  tag: str,

                  global_step: int = 0,

                  sample_rate: int = 16000,

                  scale: Union[int, float] = 1.0):
        """

        Given a single audio waveform, log a normalized recording, waveform

        plot, and spectrogram plot to TensorBoard

        """

        # only log at specified iterations and if TensorBoard is enabled
        if not self.log_iter or global_step % self.log_iter or not self.use_tb:
            return

        # normalize and log audio recording
        normalized = (scale / torch.max(
            torch.abs(x) + 1e-12, dim=-1, keepdim=True
        )[0]) * x * 0.95

        self.writer.add_audio(f"{tag}-audio",
                              normalized,
                              sample_rate=sample_rate,
                              global_step=global_step)

        if self.log_images:

            # log waveform
            self.writer.add_image(f"{tag}-waveform",
                                  plot_waveform(x, scale),
                                  global_step=global_step)

            # log spectrogram
            self.writer.add_image(f"{tag}-spectrogram",
                                  plot_spectrogram(x),
                                  global_step=global_step)

        # flush
        self.writer.flush()

    def log_norm(self,

                 x: torch.Tensor,

                 tag: str,

                 global_step: int = 0):
        """

        Plot norm of input tensor

        """

        # only log at specified iterations and if TensorBoard is enabled
        if not self.log_iter or global_step % self.log_iter or not self.use_tb:
            return

        # log norms
        norm_2 = torch.norm(x, p=2)
        norm_inf = torch.norm(x, p=float('inf'))
        self.writer.add_scalar(f'{tag}/norm-2', norm_2, global_step=global_step)
        self.writer.add_scalar(f'{tag}/norm-inf', norm_inf, global_step=global_step)

        self.writer.flush()

    def log_image(self, image: torch.Tensor, tag: str, global_step: int = 0):
        """

        Log image plot

        """

        if not self.log_images:
            return

        # only log at specified iterations and if TensorBoard is enabled
        if not self.log_iter or global_step % self.log_iter or not self.use_tb:
            return

        self.writer.add_image(
            tag,
            image,
            global_step
        )

        self.writer.flush()

    def log_filter(self,

                   amplitudes: torch.Tensor,

                   tag: str,

                   global_step: int = 0):
        """

        Plot filter controls

        """

        # only log at specified iterations and if TensorBoard is enabled
        if not self.log_iter or global_step % self.log_iter or not self.use_tb:
            return

        if self.log_images:

            self.writer.add_image(
                f'filter_controls/{tag}',
                plot_filter(amplitudes),
                global_step
            )

            self.writer.flush()

    @staticmethod
    def bytes_to_gb(size_bytes: int):
        """

        Code from: https://stackoverflow.com/a/14822210

        """
        if size_bytes == 0:
            return "0B"
        size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
        i = int(math.floor(math.log(size_bytes, 1024)))
        p = math.pow(1024, i)
        s = round(size_bytes / p, 2)
        return "%s %s" % (s, size_name[i])

    def log_cuda_memory(self, device: int = 0):

        total_memory = self.bytes_to_gb(
            torch.cuda.get_device_properties(device).total_memory
        )
        reserved_memory = self.bytes_to_gb(
            torch.cuda.memory_reserved(device)
        )
        allocated_memory = self.bytes_to_gb(
            torch.cuda.memory_allocated(device)
        )
        free_memory = self.bytes_to_gb(
            torch.cuda.memory_reserved(device) - torch.cuda.memory_allocated(
                device
            )
        )

        self.logger.info(f'\nMemory management:\n'
                         f'------------------\n'
                         f'Total: {total_memory}\n'
                         f'Reserved: {reserved_memory}\n'
                         f'Allocated: {allocated_memory}\n'
                         f'Free: {free_memory}\n')

    def checkpoint(self,

                   checkpoint: Union[nn.Module, Dict[str, Any]],

                   tag: str,

                   global_step: int = None

                   ):
        """

        Given nn.Module object or state dictionary, save to disk

        """
        ensure_dir(self.checkpoint_dir)

        if global_step is not None:
            filename = f'{tag}_{global_step}.pt'
        else:
            filename = f'{tag}.pt'

        if isinstance(checkpoint, nn.Module):
            checkpoint = checkpoint.state_dict()

        torch.save(
            checkpoint,
            self.checkpoint_dir / filename
        )

    @contextlib.contextmanager
    def force_logging(self):
        """Force Writer to log by temporarily overriding logging interval"""
        log_iter = self.log_iter
        self.log_iter = 1
        yield
        self.log_iter = log_iter