Commit ·
33edbb1
1
Parent(s): 15ee497
added bias term to loss function to encourage slightly less mse but better overalll performance across classes...
Browse files- README.md +12 -4
- forecasting/model.py +59 -3
- tests/test_bias_penalty.py +120 -0
- tests/test_training_class_weights.py +6 -1
- training/train.py +5 -0
- training/train_coupled_gaussian.yaml +3 -0
- training/train_deterministic.yaml +4 -1
README.md
CHANGED
|
@@ -312,9 +312,17 @@ Unlike inference, training expects `aia_dir`/`sxr_dir` each to have `train/`,
|
|
| 312 |
The maintained local + global Gaussian model uses one global query and a
|
| 313 |
weighted final-prediction Huber loss. Edit
|
| 314 |
`training/train_coupled_gaussian.yaml` for its architecture, mean loss,
|
| 315 |
-
uncertainty settings, data paths, and W&B settings.
|
| 316 |
-
|
| 317 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
|
| 319 |
Optional `vit_architecture.global_attention_heads`,
|
| 320 |
`global_head_hidden_dim`, and `global_attention_dropout` change only the
|
|
@@ -322,7 +330,7 @@ coupled model's global head. Omit them to use the architecture defaults saved
|
|
| 322 |
in the maintained checkpoint.
|
| 323 |
|
| 324 |
```bash
|
| 325 |
-
python training/train.py --config training/
|
| 326 |
```
|
| 327 |
|
| 328 |
Training logs to Weights & Biases and saves checkpoints to
|
|
|
|
| 312 |
The maintained local + global Gaussian model uses one global query and a
|
| 313 |
weighted final-prediction Huber loss. Edit
|
| 314 |
`training/train_coupled_gaussian.yaml` for its architecture, mean loss,
|
| 315 |
+
uncertainty settings, data paths, and W&B settings. For the released
|
| 316 |
+
deterministic model, use `training/train_deterministic.yaml`.
|
| 317 |
+
|
| 318 |
+
To encourage predictions above and below the one-to-one line to balance, set
|
| 319 |
+
`mean_loss.bias_penalty_weight` in either training config. The default is `0`;
|
| 320 |
+
`0.1` is a starting point for a sweep. The added loss is the weight times the
|
| 321 |
+
mean of the **squared signed bias within each GOES class present in the batch**,
|
| 322 |
+
using normalized log10 flux. Each represented class contributes equally; the
|
| 323 |
+
existing Huber loss retains its configured class weights. Compare
|
| 324 |
+
`val_class/<class>/bias_dex` with validation MSE and RMSE before choosing a
|
| 325 |
+
weight. A class contributes to the penalty only in batches where it appears.
|
| 326 |
|
| 327 |
Optional `vit_architecture.global_attention_heads`,
|
| 328 |
`global_head_hidden_dim`, and `global_attention_dropout` change only the
|
|
|
|
| 330 |
in the maintained checkpoint.
|
| 331 |
|
| 332 |
```bash
|
| 333 |
+
python training/train.py --config training/train_coupled_gaussian.yaml
|
| 334 |
```
|
| 335 |
|
| 336 |
Training logs to Weights & Biases and saves checkpoints to
|
forecasting/model.py
CHANGED
|
@@ -12,6 +12,32 @@ from torch.optim.lr_scheduler import CosineAnnealingLR
|
|
| 12 |
SXR_LOG_OFFSET = 1e-8
|
| 13 |
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
def normalize_sxr(unnormalized_values, sxr_norm):
|
| 16 |
"""Convert physical flux using the FOXES ``log10(F + 1e-8)`` convention."""
|
| 17 |
log_values = torch.log10(unnormalized_values + SXR_LOG_OFFSET)
|
|
@@ -51,6 +77,9 @@ class ViTLocal(pl.LightningModule):
|
|
| 51 |
loss_kwargs : dict, optional
|
| 52 |
Forwarded to SXRRegressionDynamicLoss (window_size, huber_delta,
|
| 53 |
adaptive_multipliers) — see that class for defaults.
|
|
|
|
|
|
|
|
|
|
| 54 |
diagnostic_every_n_steps : int
|
| 55 |
How often (in training steps) to log the adaptive loss's per-class
|
| 56 |
multipliers to the logger.
|
|
@@ -59,7 +88,8 @@ class ViTLocal(pl.LightningModule):
|
|
| 59 |
DEFAULT_SCHEDULER_KWARGS = {'T_max': 250, 'eta_min': 1e-7}
|
| 60 |
|
| 61 |
def __init__(self, model_kwargs, sxr_norm, base_weights=None, weight_decay=1e-5,
|
| 62 |
-
scheduler_kwargs=None, loss_kwargs=None, diagnostic_every_n_steps=200
|
|
|
|
| 63 |
super().__init__()
|
| 64 |
self.model_kwargs = model_kwargs
|
| 65 |
self.lr = model_kwargs.get('learning_rate', model_kwargs.get('lr', 1e-4))
|
|
@@ -74,6 +104,7 @@ class ViTLocal(pl.LightningModule):
|
|
| 74 |
self.scheduler_kwargs = {**self.DEFAULT_SCHEDULER_KWARGS, **(scheduler_kwargs or {})}
|
| 75 |
self.diagnostic_every_n_steps = diagnostic_every_n_steps
|
| 76 |
self.adaptive_loss = SXRRegressionDynamicLoss(base_weights=self.base_weights, **(loss_kwargs or {}))
|
|
|
|
| 77 |
self.huber_delta = self.adaptive_loss.huber_delta
|
| 78 |
self.sxr_norm = sxr_norm
|
| 79 |
|
|
@@ -124,9 +155,14 @@ class ViTLocal(pl.LightningModule):
|
|
| 124 |
# Use adaptive rare event loss. Only train batches should feed the
|
| 125 |
# per-class error history the adaptive multipliers are computed from --
|
| 126 |
# otherwise val/test performance silently leaks into training dynamics.
|
| 127 |
-
|
| 128 |
norm_preds_squeezed, sxr, sxr_un, update_tracking=(mode == "train")
|
| 129 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
# Also calculate huber loss for logging
|
| 132 |
huber_loss = F.huber_loss(norm_preds_squeezed, sxr, delta=self.huber_delta)
|
|
@@ -142,6 +178,10 @@ class ViTLocal(pl.LightningModule):
|
|
| 142 |
prog_bar=True, logger=True, sync_dist=True)
|
| 143 |
self.log("train/total_loss", loss, on_step=True, on_epoch=True,
|
| 144 |
prog_bar=True, logger=True, sync_dist=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
self.log("train/huber_loss", huber_loss, on_step=True, on_epoch=True,
|
| 146 |
prog_bar=True, logger=True, sync_dist=True)
|
| 147 |
self.log("train/mse_loss", mse_loss, on_step=True, on_epoch=True,
|
|
@@ -162,6 +202,10 @@ class ViTLocal(pl.LightningModule):
|
|
| 162 |
for key, value in multipliers.items():
|
| 163 |
self.log(f"val/adaptive/{key}", value, on_step=False, on_epoch=True)
|
| 164 |
self.log("val_total_loss", loss, on_step=False, on_epoch=True, prog_bar=True, logger=True, sync_dist=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
self.log("val_huber_loss", huber_loss, on_step=False, on_epoch=True, prog_bar=True, logger=True,
|
| 166 |
sync_dist=True)
|
| 167 |
self.log("val_mse_loss", mse_loss, on_step=False, on_epoch=True, prog_bar=True, logger=True, sync_dist=True)
|
|
@@ -1049,6 +1093,7 @@ class CoupledGaussianViTLocal(pl.LightningModule):
|
|
| 1049 |
'class_weighting',
|
| 1050 |
'class_weight_exponent',
|
| 1051 |
'class_weights',
|
|
|
|
| 1052 |
}
|
| 1053 |
# Old checkpoints include objective settings in their saved
|
| 1054 |
# hyperparameters. They do not affect inference, so accept them only
|
|
@@ -1082,6 +1127,9 @@ class CoupledGaussianViTLocal(pl.LightningModule):
|
|
| 1082 |
for key in self.NETWORK_UNCERTAINTY_KEYS
|
| 1083 |
if key in uncertainty_kwargs
|
| 1084 |
}
|
|
|
|
|
|
|
|
|
|
| 1085 |
self.model = self.NETWORK_CLASS(
|
| 1086 |
**filtered_kwargs,
|
| 1087 |
**network_uncertainty_kwargs,
|
|
@@ -1287,7 +1335,11 @@ class CoupledGaussianViTLocal(pl.LightningModule):
|
|
| 1287 |
mean_norm, target_norm, target_raw,
|
| 1288 |
)
|
| 1289 |
mean_loss = global_mean_loss
|
| 1290 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1291 |
uncertainty_active = self._uncertainty_training_is_active()
|
| 1292 |
uncertainty_loss = (
|
| 1293 |
self._uncertainty_nll_loss(
|
|
@@ -1347,6 +1399,10 @@ class CoupledGaussianViTLocal(pl.LightningModule):
|
|
| 1347 |
f'{prefix}/mean_loss', mean_loss, on_step=on_step, on_epoch=True,
|
| 1348 |
logger=True, sync_dist=True,
|
| 1349 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1350 |
self.log(f'{prefix}/total_loss', loss, on_step=on_step, on_epoch=True,
|
| 1351 |
logger=True, sync_dist=True)
|
| 1352 |
self.log(f'{prefix}/mse', mse, on_step=on_step, on_epoch=True,
|
|
|
|
| 12 |
SXR_LOG_OFFSET = 1e-8
|
| 13 |
|
| 14 |
|
| 15 |
+
def validate_bias_penalty_weight(value):
|
| 16 |
+
"""Accept only finite, nonnegative bias penalty coefficients."""
|
| 17 |
+
if (isinstance(value, bool) or not isinstance(value, (int, float))
|
| 18 |
+
or not math.isfinite(value) or value < 0):
|
| 19 |
+
raise ValueError('bias_penalty_weight must be a finite, nonnegative number')
|
| 20 |
+
return float(value)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def mean_class_signed_error_penalty(prediction, target, target_raw, weight):
|
| 24 |
+
"""Average squared signed bias across the GOES classes in a batch."""
|
| 25 |
+
residual = (prediction - target).reshape(-1)
|
| 26 |
+
flux = target_raw.reshape(-1)
|
| 27 |
+
thresholds = SXRRegressionDynamicLoss.CLASS_THRESHOLDS
|
| 28 |
+
class_index = (
|
| 29 |
+
(flux >= thresholds['c']).long()
|
| 30 |
+
+ (flux >= thresholds['m']).long()
|
| 31 |
+
+ (flux >= thresholds['x']).long()
|
| 32 |
+
)
|
| 33 |
+
sums = residual.new_zeros(4).scatter_add(0, class_index, residual)
|
| 34 |
+
counts = residual.new_zeros(4).scatter_add(
|
| 35 |
+
0, class_index, torch.ones_like(residual),
|
| 36 |
+
)
|
| 37 |
+
class_means = sums / counts.clamp_min(1)
|
| 38 |
+
return weight * class_means.square().sum() / (counts > 0).sum()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
def normalize_sxr(unnormalized_values, sxr_norm):
|
| 42 |
"""Convert physical flux using the FOXES ``log10(F + 1e-8)`` convention."""
|
| 43 |
log_values = torch.log10(unnormalized_values + SXR_LOG_OFFSET)
|
|
|
|
| 77 |
loss_kwargs : dict, optional
|
| 78 |
Forwarded to SXRRegressionDynamicLoss (window_size, huber_delta,
|
| 79 |
adaptive_multipliers) — see that class for defaults.
|
| 80 |
+
bias_penalty_weight : float
|
| 81 |
+
Coefficient on the mean squared class-specific signed error in
|
| 82 |
+
normalized log10 flux. Zero (the default) disables the penalty.
|
| 83 |
diagnostic_every_n_steps : int
|
| 84 |
How often (in training steps) to log the adaptive loss's per-class
|
| 85 |
multipliers to the logger.
|
|
|
|
| 88 |
DEFAULT_SCHEDULER_KWARGS = {'T_max': 250, 'eta_min': 1e-7}
|
| 89 |
|
| 90 |
def __init__(self, model_kwargs, sxr_norm, base_weights=None, weight_decay=1e-5,
|
| 91 |
+
scheduler_kwargs=None, loss_kwargs=None, diagnostic_every_n_steps=200,
|
| 92 |
+
bias_penalty_weight=0.0):
|
| 93 |
super().__init__()
|
| 94 |
self.model_kwargs = model_kwargs
|
| 95 |
self.lr = model_kwargs.get('learning_rate', model_kwargs.get('lr', 1e-4))
|
|
|
|
| 104 |
self.scheduler_kwargs = {**self.DEFAULT_SCHEDULER_KWARGS, **(scheduler_kwargs or {})}
|
| 105 |
self.diagnostic_every_n_steps = diagnostic_every_n_steps
|
| 106 |
self.adaptive_loss = SXRRegressionDynamicLoss(base_weights=self.base_weights, **(loss_kwargs or {}))
|
| 107 |
+
self.bias_penalty_weight = validate_bias_penalty_weight(bias_penalty_weight)
|
| 108 |
self.huber_delta = self.adaptive_loss.huber_delta
|
| 109 |
self.sxr_norm = sxr_norm
|
| 110 |
|
|
|
|
| 155 |
# Use adaptive rare event loss. Only train batches should feed the
|
| 156 |
# per-class error history the adaptive multipliers are computed from --
|
| 157 |
# otherwise val/test performance silently leaks into training dynamics.
|
| 158 |
+
base_loss, weights = self.adaptive_loss.calculate_loss(
|
| 159 |
norm_preds_squeezed, sxr, sxr_un, update_tracking=(mode == "train")
|
| 160 |
)
|
| 161 |
+
signed_error = (norm_preds_squeezed - sxr).mean()
|
| 162 |
+
bias_penalty = mean_class_signed_error_penalty(
|
| 163 |
+
norm_preds_squeezed, sxr, sxr_un, self.bias_penalty_weight,
|
| 164 |
+
)
|
| 165 |
+
loss = base_loss + bias_penalty
|
| 166 |
|
| 167 |
# Also calculate huber loss for logging
|
| 168 |
huber_loss = F.huber_loss(norm_preds_squeezed, sxr, delta=self.huber_delta)
|
|
|
|
| 178 |
prog_bar=True, logger=True, sync_dist=True)
|
| 179 |
self.log("train/total_loss", loss, on_step=True, on_epoch=True,
|
| 180 |
prog_bar=True, logger=True, sync_dist=True)
|
| 181 |
+
self.log("train/bias_dex", signed_error * float(self.sxr_norm[1]),
|
| 182 |
+
on_step=True, on_epoch=True, logger=True, sync_dist=True)
|
| 183 |
+
self.log("train/bias_penalty", bias_penalty, on_step=True,
|
| 184 |
+
on_epoch=True, logger=True, sync_dist=True)
|
| 185 |
self.log("train/huber_loss", huber_loss, on_step=True, on_epoch=True,
|
| 186 |
prog_bar=True, logger=True, sync_dist=True)
|
| 187 |
self.log("train/mse_loss", mse_loss, on_step=True, on_epoch=True,
|
|
|
|
| 202 |
for key, value in multipliers.items():
|
| 203 |
self.log(f"val/adaptive/{key}", value, on_step=False, on_epoch=True)
|
| 204 |
self.log("val_total_loss", loss, on_step=False, on_epoch=True, prog_bar=True, logger=True, sync_dist=True)
|
| 205 |
+
self.log("val/bias_dex", signed_error * float(self.sxr_norm[1]),
|
| 206 |
+
on_step=False, on_epoch=True, logger=True, sync_dist=True)
|
| 207 |
+
self.log("val/bias_penalty", bias_penalty, on_step=False,
|
| 208 |
+
on_epoch=True, logger=True, sync_dist=True)
|
| 209 |
self.log("val_huber_loss", huber_loss, on_step=False, on_epoch=True, prog_bar=True, logger=True,
|
| 210 |
sync_dist=True)
|
| 211 |
self.log("val_mse_loss", mse_loss, on_step=False, on_epoch=True, prog_bar=True, logger=True, sync_dist=True)
|
|
|
|
| 1093 |
'class_weighting',
|
| 1094 |
'class_weight_exponent',
|
| 1095 |
'class_weights',
|
| 1096 |
+
'bias_penalty_weight',
|
| 1097 |
}
|
| 1098 |
# Old checkpoints include objective settings in their saved
|
| 1099 |
# hyperparameters. They do not affect inference, so accept them only
|
|
|
|
| 1127 |
for key in self.NETWORK_UNCERTAINTY_KEYS
|
| 1128 |
if key in uncertainty_kwargs
|
| 1129 |
}
|
| 1130 |
+
self.bias_penalty_weight = validate_bias_penalty_weight(
|
| 1131 |
+
uncertainty_kwargs.get('bias_penalty_weight', 0.0)
|
| 1132 |
+
)
|
| 1133 |
self.model = self.NETWORK_CLASS(
|
| 1134 |
**filtered_kwargs,
|
| 1135 |
**network_uncertainty_kwargs,
|
|
|
|
| 1335 |
mean_norm, target_norm, target_raw,
|
| 1336 |
)
|
| 1337 |
mean_loss = global_mean_loss
|
| 1338 |
+
signed_error = (mean_norm - target_norm).mean()
|
| 1339 |
+
bias_penalty = mean_class_signed_error_penalty(
|
| 1340 |
+
mean_norm, target_norm, target_raw, self.bias_penalty_weight,
|
| 1341 |
+
)
|
| 1342 |
+
mean_objective = mean_loss + bias_penalty
|
| 1343 |
uncertainty_active = self._uncertainty_training_is_active()
|
| 1344 |
uncertainty_loss = (
|
| 1345 |
self._uncertainty_nll_loss(
|
|
|
|
| 1399 |
f'{prefix}/mean_loss', mean_loss, on_step=on_step, on_epoch=True,
|
| 1400 |
logger=True, sync_dist=True,
|
| 1401 |
)
|
| 1402 |
+
self.log(f'{prefix}/bias_dex', signed_error * self.sxr_norm[1],
|
| 1403 |
+
on_step=on_step, on_epoch=True, logger=True, sync_dist=True)
|
| 1404 |
+
self.log(f'{prefix}/bias_penalty', bias_penalty, on_step=on_step,
|
| 1405 |
+
on_epoch=True, logger=True, sync_dist=True)
|
| 1406 |
self.log(f'{prefix}/total_loss', loss, on_step=on_step, on_epoch=True,
|
| 1407 |
logger=True, sync_dist=True)
|
| 1408 |
self.log(f'{prefix}/mse', mse, on_step=on_step, on_epoch=True,
|
tests/test_bias_penalty.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from forecasting.model import (
|
| 6 |
+
CoupledGaussianViTLocal, ViTLocal, mean_class_signed_error_penalty,
|
| 7 |
+
normalize_sxr, unnormalize_sxr,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
MODEL_KWARGS = dict(
|
| 12 |
+
embed_dim=8, hidden_dim=16, num_channels=1, num_heads=1,
|
| 13 |
+
num_layers=1, patch_size=1, num_patches=4, dropout=0.0,
|
| 14 |
+
mask_mode='none',
|
| 15 |
+
)
|
| 16 |
+
COUPLED_KWARGS = dict(
|
| 17 |
+
MODEL_KWARGS, mask_mode='local', local_window=3,
|
| 18 |
+
global_patch_adjustment=True,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_class_bias_penalty_preserves_opposing_class_biases_and_has_gradient():
|
| 23 |
+
predictions = torch.tensor([1.0, -1.0], requires_grad=True)
|
| 24 |
+
target = torch.zeros(2)
|
| 25 |
+
flux = torch.tensor([1e-7, 1e-4])
|
| 26 |
+
loss = mean_class_signed_error_penalty(predictions, target, flux, 2.0)
|
| 27 |
+
torch.testing.assert_close(loss, torch.tensor(2.0))
|
| 28 |
+
loss.backward()
|
| 29 |
+
torch.testing.assert_close(predictions.grad, torch.tensor([2.0, -2.0]))
|
| 30 |
+
|
| 31 |
+
# Errors within the same class still cancel in its signed mean.
|
| 32 |
+
torch.testing.assert_close(
|
| 33 |
+
mean_class_signed_error_penalty(predictions, target,
|
| 34 |
+
torch.tensor([1e-7, 1e-7]), 2.0),
|
| 35 |
+
torch.tensor(0.0),
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# Two quiet samples and one X sample still give each class one share.
|
| 39 |
+
torch.testing.assert_close(
|
| 40 |
+
mean_class_signed_error_penalty(
|
| 41 |
+
torch.tensor([1.0, 1.0, -2.0]), torch.zeros(3),
|
| 42 |
+
torch.tensor([1e-7, 1e-7, 2e-4]), 1.0,
|
| 43 |
+
),
|
| 44 |
+
torch.tensor(2.5),
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@pytest.mark.parametrize('weight', [-1, float('nan'), float('inf'), True])
|
| 49 |
+
def test_invalid_bias_penalty_weight_rejected(weight):
|
| 50 |
+
with pytest.raises(ValueError, match='bias_penalty_weight'):
|
| 51 |
+
ViTLocal(MODEL_KWARGS, np.array([-5.0, 1.0]), bias_penalty_weight=weight)
|
| 52 |
+
with pytest.raises(ValueError, match='bias_penalty_weight'):
|
| 53 |
+
CoupledGaussianViTLocal(
|
| 54 |
+
COUPLED_KWARGS, np.array([-5.0, 1.0]),
|
| 55 |
+
uncertainty_kwargs={'enabled': False, 'bias_penalty_weight': weight},
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_coupled_total_loss_adds_penalty_without_changing_mean_loss():
|
| 60 |
+
torch.manual_seed(1)
|
| 61 |
+
model = CoupledGaussianViTLocal(
|
| 62 |
+
COUPLED_KWARGS, np.array([-5.0, 1.0]),
|
| 63 |
+
uncertainty_kwargs={'enabled': False, 'bias_penalty_weight': 0.7},
|
| 64 |
+
)
|
| 65 |
+
logged = {}
|
| 66 |
+
model.log = lambda name, value, **kwargs: logged.update({name: value})
|
| 67 |
+
images = torch.randn(3, 2, 2, 1)
|
| 68 |
+
targets = torch.tensor([0.2, 0.4, 0.6])
|
| 69 |
+
|
| 70 |
+
result = model.validation_step((images, targets), 0)
|
| 71 |
+
expected_bias = (result['mean_norm'] - targets).mean()
|
| 72 |
+
torch.testing.assert_close(logged['val/bias_dex'], expected_bias)
|
| 73 |
+
torch.testing.assert_close(logged['val/bias_penalty'], 0.7 * expected_bias.square())
|
| 74 |
+
torch.testing.assert_close(
|
| 75 |
+
result['loss'], logged['val/mean_loss'] + logged['val/bias_penalty'],
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_deterministic_total_loss_adds_penalty():
|
| 80 |
+
torch.manual_seed(2)
|
| 81 |
+
sxr_norm = np.array([-5.0, 1.0])
|
| 82 |
+
model = ViTLocal(MODEL_KWARGS, sxr_norm, bias_penalty_weight=0.4)
|
| 83 |
+
logged = {}
|
| 84 |
+
model.log = lambda name, value, **kwargs: logged.update({name: value})
|
| 85 |
+
images = torch.randn(3, 2, 2, 1)
|
| 86 |
+
targets = torch.tensor([0.2, 0.4, 0.6])
|
| 87 |
+
predictions_raw, _ = model.model(images, sxr_norm)
|
| 88 |
+
predictions_norm = normalize_sxr(predictions_raw.squeeze(), sxr_norm)
|
| 89 |
+
base_loss, _ = model.adaptive_loss.calculate_loss(
|
| 90 |
+
predictions_norm, targets, unnormalize_sxr(targets, sxr_norm),
|
| 91 |
+
update_tracking=False,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
loss = model._calculate_loss((images, targets), mode='val')
|
| 95 |
+
expected_bias = (predictions_norm - targets).mean()
|
| 96 |
+
torch.testing.assert_close(logged['val/bias_dex'], expected_bias)
|
| 97 |
+
torch.testing.assert_close(logged['val/bias_penalty'], 0.4 * expected_bias.square())
|
| 98 |
+
torch.testing.assert_close(loss, base_loss + logged['val/bias_penalty'])
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def test_coupled_bias_penalty_balances_classes_independent_of_huber_weights():
|
| 102 |
+
model = CoupledGaussianViTLocal(
|
| 103 |
+
COUPLED_KWARGS, np.array([-5.0, 1.0]),
|
| 104 |
+
uncertainty_kwargs={
|
| 105 |
+
'enabled': False, 'bias_penalty_weight': 0.5,
|
| 106 |
+
'class_weighting': 'inverse_frequency',
|
| 107 |
+
'class_weights': {
|
| 108 |
+
'quiet': 0.5, 'c_class': 1.0,
|
| 109 |
+
'm_class': 2.0, 'x_class': 4.0,
|
| 110 |
+
},
|
| 111 |
+
},
|
| 112 |
+
)
|
| 113 |
+
logged = {}
|
| 114 |
+
model.log = lambda name, value, **kwargs: logged.update({name: value})
|
| 115 |
+
result = model.validation_step(
|
| 116 |
+
(torch.randn(3, 2, 2, 1), torch.tensor([-2.0, 0.0, 2.0])), 0,
|
| 117 |
+
)
|
| 118 |
+
residual = result['mean_norm'] - result['target_norm']
|
| 119 |
+
torch.testing.assert_close(logged['val/bias_penalty'],
|
| 120 |
+
0.5 * residual.square().mean())
|
tests/test_training_class_weights.py
CHANGED
|
@@ -79,7 +79,10 @@ def test_mean_loss_weights_are_passed_to_coupled_model(tmp_path):
|
|
| 79 |
train_ds=SimpleNamespace(samples=samples, sxr_dir=tmp_path)
|
| 80 |
)
|
| 81 |
config = {
|
| 82 |
-
'mean_loss': {
|
|
|
|
|
|
|
|
|
|
| 83 |
'uncertainty': {'enabled': True},
|
| 84 |
}
|
| 85 |
|
|
@@ -90,6 +93,7 @@ def test_mean_loss_weights_are_passed_to_coupled_model(tmp_path):
|
|
| 90 |
assert base_weights is None
|
| 91 |
assert uncertainty['class_weighting'] == 'inverse_frequency'
|
| 92 |
assert uncertainty['huber_delta'] == 0.3
|
|
|
|
| 93 |
assert uncertainty['class_weights'] == config['computed_four_class_train_weights']
|
| 94 |
|
| 95 |
|
|
@@ -97,4 +101,5 @@ def test_maintained_training_config_resolves_mean_loss():
|
|
| 97 |
config = load_training_config('training/train_coupled_gaussian.yaml')
|
| 98 |
assert config['mean_loss'] == {
|
| 99 |
'class_weighting': 'inverse_frequency', 'huber_delta': 0.3,
|
|
|
|
| 100 |
}
|
|
|
|
| 79 |
train_ds=SimpleNamespace(samples=samples, sxr_dir=tmp_path)
|
| 80 |
)
|
| 81 |
config = {
|
| 82 |
+
'mean_loss': {
|
| 83 |
+
'class_weighting': 'inverse_frequency', 'huber_delta': 0.3,
|
| 84 |
+
'bias_penalty_weight': 0.2,
|
| 85 |
+
},
|
| 86 |
'uncertainty': {'enabled': True},
|
| 87 |
}
|
| 88 |
|
|
|
|
| 93 |
assert base_weights is None
|
| 94 |
assert uncertainty['class_weighting'] == 'inverse_frequency'
|
| 95 |
assert uncertainty['huber_delta'] == 0.3
|
| 96 |
+
assert uncertainty['bias_penalty_weight'] == 0.2
|
| 97 |
assert uncertainty['class_weights'] == config['computed_four_class_train_weights']
|
| 98 |
|
| 99 |
|
|
|
|
| 101 |
config = load_training_config('training/train_coupled_gaussian.yaml')
|
| 102 |
assert config['mean_loss'] == {
|
| 103 |
'class_weighting': 'inverse_frequency', 'huber_delta': 0.3,
|
| 104 |
+
'bias_penalty_weight': 0.0,
|
| 105 |
}
|
training/train.py
CHANGED
|
@@ -162,6 +162,8 @@ def configure_class_weights(config, data_module, model_type):
|
|
| 162 |
uncertainty['class_weighting'] = weighting
|
| 163 |
if 'huber_delta' in mean_loss:
|
| 164 |
uncertainty['huber_delta'] = mean_loss['huber_delta']
|
|
|
|
|
|
|
| 165 |
|
| 166 |
base_weights = loss.get('base_weights') if not coupled else None
|
| 167 |
if weighting != 'none':
|
|
@@ -342,6 +344,9 @@ def main():
|
|
| 342 |
else:
|
| 343 |
model = ViTLocal(
|
| 344 |
**common_kwargs,
|
|
|
|
|
|
|
|
|
|
| 345 |
loss_kwargs={
|
| 346 |
'window_size': loss_cfg.get('window_size', 15000),
|
| 347 |
'huber_delta': loss_cfg.get('huber_delta', 0.3),
|
|
|
|
| 162 |
uncertainty['class_weighting'] = weighting
|
| 163 |
if 'huber_delta' in mean_loss:
|
| 164 |
uncertainty['huber_delta'] = mean_loss['huber_delta']
|
| 165 |
+
if 'bias_penalty_weight' in mean_loss:
|
| 166 |
+
uncertainty['bias_penalty_weight'] = mean_loss['bias_penalty_weight']
|
| 167 |
|
| 168 |
base_weights = loss.get('base_weights') if not coupled else None
|
| 169 |
if weighting != 'none':
|
|
|
|
| 344 |
else:
|
| 345 |
model = ViTLocal(
|
| 346 |
**common_kwargs,
|
| 347 |
+
bias_penalty_weight=config.get('mean_loss', {}).get(
|
| 348 |
+
'bias_penalty_weight', 0.0,
|
| 349 |
+
),
|
| 350 |
loss_kwargs={
|
| 351 |
'window_size': loss_cfg.get('window_size', 15000),
|
| 352 |
'huber_delta': loss_cfg.get('huber_delta', 0.3),
|
training/train_coupled_gaussian.yaml
CHANGED
|
@@ -18,6 +18,9 @@ model_type: coupled_uncertainty
|
|
| 18 |
mean_loss:
|
| 19 |
class_weighting: inverse_frequency
|
| 20 |
huber_delta: 0.30
|
|
|
|
|
|
|
|
|
|
| 21 |
uncertainty:
|
| 22 |
enabled: true
|
| 23 |
initial_relative_std: 1
|
|
|
|
| 18 |
mean_loss:
|
| 19 |
class_weighting: inverse_frequency
|
| 20 |
huber_delta: 0.30
|
| 21 |
+
# Optional mean squared signed bias across quiet/C/M/X classes in each batch.
|
| 22 |
+
# Classes present in a batch contribute equally; 0 keeps the original loss.
|
| 23 |
+
bias_penalty_weight: 0.0
|
| 24 |
uncertainty:
|
| 25 |
enabled: true
|
| 26 |
initial_relative_std: 1
|
training/train_deterministic.yaml
CHANGED
|
@@ -6,7 +6,7 @@
|
|
| 6 |
# data/build_dataset.py produces).
|
| 7 |
#
|
| 8 |
# Usage:
|
| 9 |
-
# python training/train.py --config training/
|
| 10 |
# =============================================================================
|
| 11 |
wavelengths: [94, 131, 171, 193, 211, 304, 335]
|
| 12 |
|
|
@@ -23,6 +23,9 @@ epochs: 250
|
|
| 23 |
# Compute quiet/C/M/X weights from training targets before starting.
|
| 24 |
mean_loss:
|
| 25 |
class_weighting: inverse_frequency
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
vit_architecture:
|
| 28 |
embed_dim: 256
|
|
|
|
| 6 |
# data/build_dataset.py produces).
|
| 7 |
#
|
| 8 |
# Usage:
|
| 9 |
+
# python training/train.py --config training/train_deterministic.yaml
|
| 10 |
# =============================================================================
|
| 11 |
wavelengths: [94, 131, 171, 193, 211, 304, 335]
|
| 12 |
|
|
|
|
| 23 |
# Compute quiet/C/M/X weights from training targets before starting.
|
| 24 |
mean_loss:
|
| 25 |
class_weighting: inverse_frequency
|
| 26 |
+
# Optional mean squared signed bias across quiet/C/M/X classes in each batch.
|
| 27 |
+
# Classes present in a batch contribute equally; 0 keeps the original loss.
|
| 28 |
+
bias_penalty_weight: 0.0
|
| 29 |
|
| 30 |
vit_architecture:
|
| 31 |
embed_dim: 256
|