File size: 12,122 Bytes
fc16538
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# TRI-VIDAR - Copyright 2022 Toyota Research Institute.  All rights reserved.

from collections import OrderedDict
from copy import deepcopy

import torch
import torch.nn as nn
import wandb

from vidar.utils.config import cfg_has
from vidar.utils.distributed import world_size
from vidar.utils.logging import pcolor
from vidar.utils.types import is_dict, is_tensor, is_seq, is_namespace
from vidar.utils.viz import viz_depth, viz_inv_depth, viz_normals, viz_optical_flow, viz_camera


class WandbLogger:
    """
    Wandb logger class to monitor training

    Parameters
    ----------
    cfg : Config
        Configuration with parameters
    verbose : Bool
        Print information on screen if enabled
    """
    def __init__(self, cfg, verbose=False):
        super().__init__()

        self.num_logs = {
            'train': cfg_has(cfg, 'num_train_logs', 0),
            'val': cfg_has(cfg, 'num_validation_logs', 0),
            'test': cfg_has(cfg, 'num_test_logs', 0),
        }

        self._name = cfg.name if cfg_has(cfg, 'name') else None
        self._dir = cfg.folder
        self._entity = cfg.entity
        self._project = cfg.project

        self._tags = cfg_has(cfg, 'tags', '')
        self._notes = cfg_has(cfg, 'notes', '')

        self._id = None
        self._anonymous = None
        self._log_model = True

        self._experiment = self._create_experiment()
        self._metrics = OrderedDict()

        self.only_first = cfg_has(cfg, 'only_first', False)

        cfg.name = self.run_name
        cfg.url = self.run_url

        if verbose:
            self.print()

    @staticmethod
    def finish():
        """Finish wandb session"""
        wandb.finish()

    def print(self):
        """Print information on screen"""

        font_base = {'color': 'red', 'attrs': ('bold', 'dark')}
        font_name = {'color': 'red', 'attrs': ('bold',)}
        font_underline = {'color': 'red', 'attrs': ('underline',)}

        print(pcolor('#' * 60, **font_base))
        print(pcolor('### WandB: ', **font_base) + \
              pcolor('{}'.format(self.run_name), **font_name))
        print(pcolor('### ', **font_base) + \
              pcolor('{}'.format(self.run_url), **font_underline))
        print(pcolor('#' * 60, **font_base))

    def __getstate__(self):
        """Get the current logger state"""
        state = self.__dict__.copy()
        state['_id'] = self._experiment.id if self._experiment is not None else None
        state['_experiment'] = None
        return state

    def _create_experiment(self):
        """Creates and returns a new experiment"""
        experiment = wandb.init(
            name=self._name, dir=self._dir, project=self._project,
            anonymous=self._anonymous, reinit=True, id=self._id, notes=self._notes,
            resume='allow', tags=self._tags, entity=self._entity
        )
        wandb.run.save()
        return experiment

    def watch(self, model: nn.Module, log='gradients', log_freq=100):
        """Watch training parameters"""
        self.experiment.watch(model, log=log, log_freq=log_freq)

    @property
    def experiment(self):
        """Returns the experiment (creates a new if it doesn't exist)"""
        if self._experiment is None:
            self._experiment = self._create_experiment()
        return self._experiment

    @property
    def run_name(self):
        """Returns run name"""
        return wandb.run.name if self._experiment else None

    @property
    def run_url(self):
        """Returns run URL"""
        return f'https://app.wandb.ai/' \
               f'{wandb.run.entity}/' \
               f'{wandb.run.project}/runs/' \
               f'{wandb.run.id}' if self._experiment else None

    def log_config(self, cfg):
        """Log model configuration"""
        cfg = recursive_convert_config(deepcopy(cfg))
        self.experiment.config.update(cfg, allow_val_change=True)

    def log_metrics(self, metrics):
        """Log training metrics"""
        self._metrics.update(metrics)
        if 'epochs' in metrics or 'samples' in metrics:
            self.experiment.log(self._metrics)
            self._metrics.clear()

    def log_images(self, batch, output, prefix, ontology=None):
        """
        Log images depending on its nature

        Parameters
        ----------
        batch : Dict
            Dictionary containing batch information
        output : Dict
            Dictionary containing output information
        prefix : String
            Prefix string for the log name
        ontology : Dict
            Dictionary with ontology information
        """
        for data, suffix in zip([batch, output['predictions']], ['-gt', '-pred']):
            for key in data.keys():
                if key.startswith('rgb'):
                    self._metrics.update(log_rgb(
                        key, prefix + suffix, data, only_first=self.only_first))
                elif key.startswith('depth'):
                    self._metrics.update(log_depth(
                        key, prefix + suffix, data, only_first=self.only_first))
                elif key.startswith('inv_depth'):
                    self._metrics.update(log_inv_depth(
                        key, prefix + suffix, data, only_first=self.only_first))
                elif 'normals' in key:
                    self._metrics.update(log_normals(
                        key, prefix + suffix, data, only_first=self.only_first))
                elif key.startswith('stddev'):
                    self._metrics.update(log_stddev(
                        key, prefix + suffix, data, only_first=self.only_first))
                elif key.startswith('logvar'):
                    self._metrics.update(log_logvar(
                        key, prefix + suffix, data, only_first=self.only_first))
                elif 'optical_flow' in key:
                    self._metrics.update(log_optical_flow(
                        key, prefix + suffix, data, only_first=self.only_first))
                elif 'mask' in key or 'valid' in key:
                    self._metrics.update(log_rgb(
                        key, prefix, data, only_first=self.only_first))
                # elif 'camera' in key:
                #     self._metrics.update(log_camera(
                #         key, prefix + suffix, data, only_first=self.only_first))
                # elif 'uncertainty' in key:
                #     self._metrics.update(log_uncertainty(key, prefix, data))
                # elif 'semantic' in key and ontology is not None:
                #     self._metrics.update(log_semantic(key, prefix, data, ontology=ontology))
                # if 'scene_flow' in key:
                #     self._metrics.update(log_scene_flow(key, prefix_idx, data))
                # elif 'score' in key:
                #     # Log score as image heatmap
                #     self._metrics.update(log_keypoint_score(key, prefix, data))

    def log_data(self, mode, batch, output, dataset, prefix, ontology=None):
        """Helper function used to log images"""
        idx = batch['idx'][0]
        num_logs = self.num_logs[mode]
        if num_logs > 0:
            interval = (len(dataset) // world_size() // num_logs) * world_size()
            if interval == 0 or (idx % interval == 0 and idx < interval * num_logs):
                prefix = '{}-{}-{}'.format(mode, prefix, batch['idx'][0].item())
                # batch, output = prepare_logging(batch, output)
                self.log_images(batch, output, prefix, ontology=ontology)


def recursive_convert_config(cfg):
    """Convert configuration to dictionary recursively"""
    cfg = cfg.__dict__
    for key, val in cfg.items():
        if is_namespace(val):
            cfg[key] = recursive_convert_config(val)
    return cfg


def prep_image(key, prefix, image):
    """Prepare image for logging"""
    if is_tensor(image):
        if image.dim() == 2:
            image = image.unsqueeze(0)
        if image.dim() == 4:
            image = image[0]
        image = image.detach().permute(1, 2, 0).cpu().numpy()
    prefix_key = '{}-{}'.format(prefix, key)
    return {prefix_key: wandb.Image(image, caption=key)}


def log_sequence(key, prefix, data, i, only_first, fn):
    """Logs a sequence of images (list, tuple or dict)"""
    log = {}
    if is_dict(data):
        for ctx, dict_val in data.items():
            if is_seq(dict_val):
                if only_first:
                    dict_val = dict_val[:1]
                for idx, list_val in enumerate(dict_val):
                    if list_val.dim() == 5:
                        for j in range(list_val.shape[1]):
                            log.update(fn('%s(%s_%d)_%d' % (key, str(ctx), j, idx), prefix, list_val[:, j], i))
                    else:
                        log.update(fn('%s(%s)_%d' % (key, str(ctx), idx), prefix, list_val, i))
            else:
                if dict_val.dim() == 5:
                    for j in range(dict_val.shape[1]):
                        log.update(fn('%s(%s_%d)' % (key, str(ctx), j), prefix, dict_val[:, j], i))
                else:
                    log.update(fn('%s(%s)' % (key, str(ctx)), prefix, dict_val, i))
    elif is_seq(data):
        if only_first:
            data = data[:1]
        for idx, list_val in enumerate(data):
            log.update(fn('%s_%d' % (key, idx), prefix, list_val, i))
    else:
        log.update(fn('%s' % key, prefix, data, i))
    return log


def log_rgb(key, prefix, batch, i=0, only_first=None):
    """Log RGB image"""
    rgb = batch[key] if is_dict(batch) else batch
    if is_seq(rgb) or is_dict(rgb):
        return log_sequence(key, prefix, rgb, i, only_first, log_rgb)
    return prep_image(key, prefix, rgb[i].clamp(min=0.0, max=1.0))


def log_depth(key, prefix, batch, i=0, only_first=None):
    """Log depth map"""
    depth = batch[key] if is_dict(batch) else batch
    if is_seq(depth) or is_dict(depth):
        return log_sequence(key, prefix, depth, i, only_first, log_depth)
    return prep_image(key, prefix, viz_depth(depth[i], filter_zeros=True))


def log_inv_depth(key, prefix, batch, i=0, only_first=None):
    """Log inverse depth map"""
    inv_depth = batch[key] if is_dict(batch) else batch
    if is_seq(inv_depth) or is_dict(inv_depth):
        return log_sequence(key, prefix, inv_depth, i, only_first, log_inv_depth)
    return prep_image(key, prefix, viz_inv_depth(inv_depth[i]))


def log_normals(key, prefix, batch, i=0, only_first=None):
    """Log normals"""
    normals = batch[key] if is_dict(batch) else batch
    if is_seq(normals) or is_dict(normals):
        return log_sequence(key, prefix, normals, i, only_first, log_normals)
    return prep_image(key, prefix, viz_normals(normals[i]))


def log_optical_flow(key, prefix, batch, i=0, only_first=None):
    """Log optical flow"""
    optical_flow = batch[key] if is_dict(batch) else batch
    if is_seq(optical_flow) or is_dict(optical_flow):
        return log_sequence(key, prefix, optical_flow, i, only_first, log_optical_flow)
    return prep_image(key, prefix, viz_optical_flow(optical_flow[i]))


def log_stddev(key, prefix, batch, i=0, only_first=None):
    """Log standard deviation"""
    stddev = batch[key] if is_dict(batch) else batch
    if is_seq(stddev) or is_dict(stddev):
        return log_sequence(key, prefix, stddev, i, only_first, log_stddev)
    return prep_image(key, prefix, viz_inv_depth(stddev[i], colormap='jet'))


def log_logvar(key, prefix, batch, i=0, only_first=None):
    """Log standard deviation"""
    logvar = batch[key] if is_dict(batch) else batch
    if is_seq(logvar) or is_dict(logvar):
        return log_sequence(key, prefix, logvar, i, only_first, log_logvar)
    return prep_image(key, prefix, viz_inv_depth(torch.exp(logvar[i]), colormap='jet'))


def log_camera(key, prefix, batch, i=0, only_first=None):
    """Log camera"""
    camera = batch[key] if is_dict(batch) else batch
    if is_seq(camera) or is_dict(camera):
        return log_sequence(key, prefix, camera, i, only_first, log_camera)
    return prep_image(key, prefix, viz_camera(camera[i]))