File size: 8,156 Bytes
3e56913
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from pathlib import Path
from typing import Any, Optional, Tuple

import cv2
import matplotlib.pyplot as plt
import numpy as np
import pytorch_lightning as pl
import torch
from PIL import Image, ImageDraw
from pytorch_lightning.callbacks import Callback
from pytorch_lightning.utilities import rank_zero_only

from typing import Dict, Callable
from pytorch_lightning import Callback, LightningModule, Trainer
from functools import wraps


from utils.custom_types import DrivingExample
from utils.logging_project import rank_zero_print
from utils.projection import get_camera_intrinsics, project_points


_STEPS_TO_FIRST_IDX: Dict[int, int] = {}


def once_per_step(function: Callable[[Callback, Trainer, LightningModule, Any, Any, int], None]) -> Callable:
    """
    ``on_train_batch_end`` gets called by pytorch lightning an ``accumulate_grad_batches`` number of times per global step.
    Sometimes ``on_train_batch_end`` is intended per optimisation step, not per each forward pass of a batch.
    This wrapper provides such behaviour, in lack of having found an integrated pytorch lightning way so far*.

    Note:
        Wrapper specifically for `on_train_batch_end` from a pl `Callback`, in regards to the function signature.
    """

    # * `on_before_optimizer_step` is available but gets called before a step is finished, potentially leading to
    #   unexpected behaviour (e.g. report step timings that cut across steps, etc).
    # NOTE: The `_STEPS_TO_FIRST_IDX` global dict is not threadsafe, but `on_train_batch_end` is expected to only be
    #       called sequentially per process.
    # NOTE(technical): When `on_train_batch_end` is called, `trainer.global_step` is already updated. Hence taking the
    # first occurring `batch_idx` for a specific step is effectively the last `batch_idx` from the previous step and the
    # reporting thus is correct.
    @wraps(function)
    def only_on_first_go(
        self: Callback, trainer: Trainer, pl_module: LightningModule, outputs: Any, batch: Any, batch_idx: int
    ) -> None:
        if not all(
            (
                isinstance(self, Callback),
                isinstance(trainer, Trainer),
                isinstance(pl_module, LightningModule),
                isinstance(batch_idx, int),
            )
        ):
            raise ValueError(
                "Only use this decorator on `pl.Callback`'s `on_train_batch_end` function!",
            )
        global_step = trainer.global_step
        if global_step not in _STEPS_TO_FIRST_IDX:
            _STEPS_TO_FIRST_IDX[global_step] = batch_idx

        if _STEPS_TO_FIRST_IDX[global_step] == batch_idx:
            return function(self, trainer, pl_module, outputs, batch, batch_idx)
        return None

    return only_on_first_go


class VisualiseCallback(Callback):
    def __init__(self, interval: int, save_dir: str = "visualisations"):
        super().__init__()
        self.interval = interval
        self.save_dir = Path(save_dir)

    @once_per_step
    @torch.no_grad
    def on_train_batch_end(  # pylint: disable=too-many-statements
        self,
        trainer: pl.Trainer,
        pl_module: pl.LightningModule,
        outputs: Any,
        batch: DrivingExample,
        batch_idx: int,
    ):
        if trainer.global_step % self.interval != 0:
            return

        with torch.amp.autocast("cuda", enabled=True):
            # Forward with sampling
            speed_wps, route = pl_module.forward(batch.driving_input)

        try:
            self._visualise_training_examples(batch, speed_wps, trainer, pl_module, 'waypoints')
            self._visualise_training_examples(batch, route, trainer, pl_module, 'route')

            # visualise_cameras(batch, pl_module, trainer, route, speed_wps)
            
            rank_zero_print("visualised_training_example")
            # _LOGGER.info("visualised_training_example")
        except Exception as e:  # pylint: disable=broad-except
            rank_zero_print("visualise_training_examples", e)
            pass
            # _LOGGER.exception("visualise_training_examples", e)
        if hasattr(pl_module, "clear_cache"):
            rank_zero_print("clearing_cache")
            # Clear cache associated with decoding language model
            # _LOGGER.info("clearing_cache")
            pl_module.clear_cache()

    @rank_zero_only
    def _visualise_training_examples(
        self,
        batch: DrivingExample,
        waypoints,
        trainer: pl.Trainer,
        pl_module: pl.LightningModule,
        name: str,
    ):
        if waypoints is None:
            return

        # only visualise max 16 examples
        # if len(batch.run_id) > 16:
        if name == 'waypoints':
            waypoint_vis = visualise_waypoints(batch, waypoints)
        elif name == 'route':
            waypoint_vis = visualise_waypoints(batch, waypoints, route=True)
        image = Image.fromarray(waypoint_vis)
        self.save_dir.mkdir(parents=True, exist_ok=True)
        save_path = self.save_dir / f"step_{trainer.global_step:08d}_{name}.png"
        image.save(save_path)

        for logger in getattr(trainer, "loggers", []) or []:
            if hasattr(logger, "log_image"):
                logger.log_image(f"visualise/{name}", images=[image], step=trainer.global_step)


def tensor_to_numpy(tensor: torch.Tensor) -> np.ndarray:
    """Convert tensor to numpy; bf16/fp16 are not supported by numpy directly."""
    return tensor.detach().float().cpu().numpy()


def fig_to_np(fig):
    fig.tight_layout()
    fig.canvas.draw()
    w, h = fig.canvas.get_width_height()
    data = np.frombuffer(fig.canvas.buffer_rgba(), dtype=np.uint8).reshape(h, w, 4)
    return data[:, :, :3].copy()

def _org_trajectory(batch: DrivingExample, route: bool, n: int):
    label = batch.driving_label
    if route:
        if label.route_adjusted_org is None:
            return None, None
        org = tensor_to_numpy(label.route_adjusted_org[:, :n, :])
        gt = tensor_to_numpy(label.route_adjusted[:, :n, :])
    else:
        if label.waypoints_org is None:
            return None, None
        org = tensor_to_numpy(label.waypoints_org[:, :n, :])
        gt = tensor_to_numpy(label.waypoints[:, :n, :])
    if np.allclose(org, gt, atol=1e-3):
        return None, None
    return org, gt

@torch.no_grad()
def visualise_waypoints(batch: DrivingExample, waypoints, route=False):
    assert batch.driving_label is not None

    n = 11
    if route:
        n = 20
    fig = plt.figure(figsize=(10, 10))
    try:
        if route:
            gt_waypoints = tensor_to_numpy(batch.driving_label.route_adjusted[:, :n, :])
        else:
            gt_waypoints = tensor_to_numpy(batch.driving_label.waypoints[:, :n, :])
        pred_waypoints = tensor_to_numpy(waypoints[:, :n])
        org_waypoints, _ = _org_trajectory(batch, route=route, n=n)
        b = gt_waypoints.shape[0]
        # visualise max 16 examples
        b = min(b, 16)
        rows = int(np.ceil(b / 4))
        cols = min(b, 4)

        # add space for text
        fig.subplots_adjust(hspace=0.8)
        for i in range(b):
            ax = fig.add_subplot(rows, cols, i + 1)
            # Predicted waypoints
            ax.scatter(-pred_waypoints[i, :, 1], pred_waypoints[i, :, 0], marker="o", c="b")
            ax.plot(-pred_waypoints[i, :, 1], pred_waypoints[i, :, 0], c="b")
            # Ground truth waypoints (i.e. ideal waypoints)
            ax.scatter(-gt_waypoints[i, :, 1], gt_waypoints[i, :, 0], marker="x", c="g")
            ax.plot(-gt_waypoints[i, :, 1], gt_waypoints[i, :, 0], c="g")
            # Original trajectory before dreamer instruction (only when different from GT)
            if org_waypoints is not None:
                ax.scatter(-org_waypoints[i, :, 1], org_waypoints[i, :, 0], marker="o", c="r", alpha=0.7)
                ax.plot(-org_waypoints[i, :, 1], org_waypoints[i, :, 0], c="r", alpha=0.7)
            ax.set_title(f"waypoints {i}")
            ax.grid()
            ax.set_aspect("equal", adjustable="box")
            ax.set_box_aspect(1.5)

        return fig_to_np(fig)
    finally:
        plt.close(fig)