File size: 8,994 Bytes
dbd79bd |
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 |
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
# #
# This file was created by: Alberto Palomo Alonso #
# Universidad de Alcalá - Escuela Politécnica Superior #
# #
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
# Import statements:
import torch
import logging
import numpy as np
import io
import math
import random
from PIL import Image
from matplotlib import pyplot as plt
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms
from .functions import REG_FUNCTION_MAP
# - # - # - # - # - # - # - # - # - # - # - # - # - # - # - #
# REGISTER #
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
@torch.no_grad()
def register(
flags: dict,
tensor: float | torch.Tensor,
valid_mask: torch.Tensor,
epoch: int,
writer: SummaryWriter,
logger: logging.Logger,
tensorboard_required: bool,
parameter_name: str = ''
):
"""
Registers a parameter according to the register flags (DEFAULT_WATCHER style).
:param flags: A specific watch flag.
:param tensor: The tensor to register.
:param valid_mask: The valid mask to apply.
:param epoch: The current epoch.
:param writer: The tensorboard writer.
:param logger: The logger.
:param tensorboard_required: Whether the tensorboard writer is required.
:param parameter_name: The name of the parameter.
:return:
"""
# 1. Detect tensor type:
if isinstance(tensor, torch.nn.Parameter):
flag_type = 'parameters'
elif isinstance(tensor, torch.Tensor):
# Intermediate activation:
flag_type = 'activations'
elif isinstance(tensor, float):
flag_type = 'train'
else:
raise ValueError(f"{type(tensor)} is not a torch.nn.Parameter or torch.Tensor.")
# 2. Build the tensor names:
safe_names = list()
# Check if the group is active:
if flag_type == 'parameters':
for flag_key, flag_value in flags['parameters'].items():
# Add if active:
if flag_value:
safe_names.append((f'{flag_type}/{flag_key}/{parameter_name}/', flag_key))
else:
safe_names.append((f'{flag_type}/{parameter_name}/', ''))
# 3. Write and compute each required variable:
for name, flag_key in safe_names:
# Compute the value:
transformation = None
if isinstance(tensor, torch.nn.Parameter):
if tensor.grad is not None and 'grad' in flag_key:
transformation = REG_FUNCTION_MAP[flag_key](tensor, valid_mask)
else:
transformation = float(tensor) if tensor is not None else None
# Write the value in tensorboard:
if transformation is not None:
write_tensorboard(
name=name,
value=transformation,
epoch=epoch,
writer=writer,
logger=logger,
tensorboard_required=tensorboard_required,
)
# - # - # - # - # - # - # - # - # - # - # - # - # - # - # - #
# REPLAY #
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
@torch.no_grad()
def register_replay(
predicted: torch.Tensor,
target: torch.Tensor,
epoch: int,
writer: SummaryWriter,
logger: logging.Logger,
valid_mask: torch.Tensor = Ellipsis,
element: int = None,
tensorboard_required: bool = True,
) -> plt.Figure:
"""
Registers a replay as an image.
:param predicted: The predicted value (prediction).
:param target: The expected value (labels).
:param epoch: The current epoch.
:param writer: The tensorboard writer.
:param logger: The logger.
:param valid_mask: A valid mask tensor of same shape. False positions are ignored (valid mask).
:param element: The element to register, None chooses a random batch element.
:param tensorboard_required: Whether the tensorboard writer is required.
:return: A matplotlib figure.
"""
# Choose random element:
if element is None:
element = random.randint(0, len(predicted) - 1)
else:
element = min(len(predicted) - 1, max(0, element))
# Convert the chosen to numpy:
predicted_np = predicted[element].detach().cpu().numpy()
target_np = target[element].detach().cpu().numpy()
# Categorical to vector:
if not target_np.shape:
target_np_aux = np.zeros_like(predicted_np)
target_np_aux[target_np] = 1.
target_np = target_np_aux
del target_np_aux
# Mask the valid positions:
if valid_mask is not None:
mask_np = valid_mask[element].detach().cpu().numpy().astype(bool)
else:
mask_np = np.ones_like(predicted_np, dtype=bool)
# Apply mask and flatten:
predicted_flat = predicted_np[mask_np].flatten()
target_flat = target_np[mask_np].flatten()
# Compute square size B:
s = predicted_flat.shape[0]
b = math.ceil(math.sqrt(s))
total = b * b
pad = total - s
# Pad with zeros:
predicted_padded = np.pad(predicted_flat, (0, pad), constant_values=0.0).reshape(b, b)
target_padded = np.pad(target_flat, (0, pad), constant_values=0.0).reshape(b, b)
# Build figure:
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
plot_with_values(axs[0], predicted_padded, "Predicted (y_hat)")
plot_with_values(axs[1], target_padded, "Target (y)")
plt.tight_layout()
write_tensorboard(
'replay/',
fig,
epoch=epoch,
writer=writer,
logger=logger,
tensorboard_required=tensorboard_required,
)
return fig
def plot_with_values(ax, data, title):
"""
Plots data with values and title.
:param ax: A matplotlib axes.
:param data: A numpy array.
:param title: The title of the plot.
:return:
"""
ax.imshow(data, cmap='viridis', interpolation='nearest')
ax.set_title(title)
ax.axis('off')
for i in range(data.shape[0]):
for j in range(data.shape[1]):
text_color = "white" if data[i, j] < 0.5 else "black"
ax.text(j, i, f"{data[i, j]:.2f}", ha="center", va="center", color=text_color, fontsize=8)
# - # - # - # - # - # - # - # - # - # - # - # - # - # - # - #
# WRITE ON BASE #
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
def write_tensorboard(
name: str,
value: int | float | plt.Figure | np.ndarray | torch.Tensor,
epoch: int,
writer: SummaryWriter,
logger: logging.Logger,
tensorboard_required: bool = True,
) -> None:
"""
Write to tensorboard.
:param name: The name of the tensorboard.
:param value: The value to write.
:param epoch: The current epoch.
:param writer: The tensorboard writer.
:param logger: The logger.
:param tensorboard_required: Whether the tensorboard writer is required.
"""
# Check if the writer is None
if writer is None:
if tensorboard_required:
logger.warning("Writer is None. Please set the writer first.")
return
# Check if the value is None
if value is None:
logger.warning("Value is None. Please set the value first.")
return
# Check if the name is None
if name is None:
logger.warning("Name is None. Please set the name first.")
return
# Type check:
if isinstance(value, int):
writer.add_scalar(name, float(value), epoch)
elif isinstance(value, float):
writer.add_scalar(name, value, epoch)
elif isinstance(value, torch.Tensor):
value = value.detach().cpu().numpy()
writer.add_histogram(name, value, epoch)
elif isinstance(value, list):
value = np.array(value)
writer.add_histogram(name, value, epoch)
elif isinstance(value, np.ndarray):
writer.add_histogram(name, value, epoch)
elif isinstance(value, str):
writer.add_text(name, value, epoch)
elif isinstance(value, bytes):
image = Image.open(io.BytesIO(value))
transform = transforms.ToTensor()
value = transform(image)
writer.add_image(name, value, epoch)
elif isinstance(value, plt.Figure):
buf = io.BytesIO()
value.savefig(buf, format='png')
buf.seek(0)
image = Image.open(buf)
image = transforms.ToTensor()(image)
writer.add_image(name, image, epoch)
plt.close()
else:
raise ValueError(f"Type {type(value)} not supported.")
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
# END OF FILE #
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
|