1import pathlib
2from typing import Dict
3from typing import Optional
4from typing import Union
5
6import torch
7from torch.utils.tensorboard import SummaryWriter
8
9
[docs]
10class TensorboardManager:
11 def __init__(
12 self,
13 log_name: Optional[str] = None,
14 log_directory: Optional[Union[str, pathlib.Path]] = None,
15 ):
16 """A tensorboard manager for simplified tensorboard logging.
17
18 Args:
19 log_name: The name of the tensorboard log run.
20 log_directory: An explicit directory to write logs to. When provided,
21 it takes precedence over ``log_name``.
22 """
23 if log_directory is not None:
24 self.log_directory = str(log_directory)
25 else:
26 if log_name is None:
27 log_name = "fill this" ##########
28 self.log_directory = f"../runs/{log_name}"
29 """The directory where tensorboard logs are saved."""
[docs]
30 self.summary_writer = SummaryWriter(log_dir=self.log_directory)
31 """The tensorboard summary writer."""
32
[docs]
33 def log_metrics(self, metrics: Dict[str, float], global_step: int):
34 """Log metrics to tensorboard.
35
36 Args:
37 metrics: A dictionary mapping metric names to values.
38 global_step: The step at which the metrics are recorded.
39 """
40 for metric_name, value in metrics.items():
41 self.summary_writer.add_scalar(
42 metric_name, value, global_step=global_step
43 )
44
[docs]
45 def log_images(self, tag: str, images: torch.Tensor, timestep: int):
46 """Log images to tensorboard.
47
48 Args:
49 tag: The name to give the images in tensorboard.
50 images: A tensor representing the images to log.
51 timestep: The timestep at which the images are produced.
52
53 """
54 self.summary_writer.add_images(
55 tag=tag, img_tensor=images, global_step=timestep
56 )
57
[docs]
58 def log_text(self, tag: str, text: str, global_step: int = 0):
59 """Log text to tensorboard.
60
61 Args:
62 tag: The name to give the text in tensorboard.
63 text: The text to log (rendered as markdown by tensorboard).
64 global_step: The step at which the text is recorded.
65 """
66 self.summary_writer.add_text(tag, text, global_step=global_step)
67
[docs]
68 def log_weights(self, model: torch.nn.Module, global_step: int):
69 """Log a histogram of every model parameter to tensorboard.
70
71 Args:
72 model: The model whose parameters are logged.
73 global_step: The step at which the weights are recorded.
74 """
75 for name, parameter in model.named_parameters():
76 self.summary_writer.add_histogram(
77 f"Weights/{name}", parameter.detach().float(), global_step=global_step
78 )