Commit ·
71f2b7e
1
Parent(s): c2c96e5
Updated model to include inverted attention naming scheme
Browse files
forecasting/models/vit_patch_model_local.py
CHANGED
|
@@ -5,11 +5,9 @@ import numpy as np
|
|
| 5 |
import torch
|
| 6 |
import torch.nn as nn
|
| 7 |
import torch.nn.functional as F
|
| 8 |
-
from torch.utils.checkpoint import checkpoint
|
| 9 |
import pytorch_lightning as pl
|
| 10 |
from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts
|
| 11 |
|
| 12 |
-
#norm = np.load("/mnt/data/ML-Ready_clean/mixed_data/SXR/normalized_sxr.npy")
|
| 13 |
|
| 14 |
def normalize_sxr(unnormalized_values, sxr_norm):
|
| 15 |
"""Convert from unnormalized to normalized space"""
|
|
@@ -17,9 +15,11 @@ def normalize_sxr(unnormalized_values, sxr_norm):
|
|
| 17 |
normalized = (log_values - float(sxr_norm[0].item())) / float(sxr_norm[1].item())
|
| 18 |
return normalized
|
| 19 |
|
|
|
|
| 20 |
def unnormalize_sxr(normalized_values, sxr_norm):
|
| 21 |
return 10 ** (normalized_values * float(sxr_norm[1].item()) + float(sxr_norm[0].item())) - 1e-8
|
| 22 |
|
|
|
|
| 23 |
class ViTLocal(pl.LightningModule):
|
| 24 |
def __init__(self, model_kwargs, sxr_norm, base_weights=None):
|
| 25 |
super().__init__()
|
|
@@ -30,12 +30,10 @@ class ViTLocal(pl.LightningModule):
|
|
| 30 |
filtered_kwargs.pop('lr', None)
|
| 31 |
filtered_kwargs.pop('num_classes', None)
|
| 32 |
self.model = VisionTransformerLocal(**filtered_kwargs)
|
| 33 |
-
#Set the base weights based on the number of samples in each class within training data
|
| 34 |
self.base_weights = base_weights
|
| 35 |
self.adaptive_loss = SXRRegressionDynamicLoss(window_size=15000, base_weights=self.base_weights)
|
| 36 |
self.sxr_norm = sxr_norm
|
| 37 |
-
self.use_gradient_checkpointing = True
|
| 38 |
-
|
| 39 |
|
| 40 |
def forward(self, x, return_attention=True):
|
| 41 |
return self.model(x, self.sxr_norm, return_attention=return_attention)
|
|
@@ -72,7 +70,7 @@ class ViTLocal(pl.LightningModule):
|
|
| 72 |
|
| 73 |
def _calculate_loss(self, batch, mode="train"):
|
| 74 |
imgs, sxr = batch
|
| 75 |
-
raw_preds, raw_patch_contributions = self.model(imgs,self.sxr_norm)
|
| 76 |
raw_preds_squeezed = torch.squeeze(raw_preds)
|
| 77 |
sxr_un = unnormalize_sxr(sxr, self.sxr_norm)
|
| 78 |
|
|
@@ -82,7 +80,7 @@ class ViTLocal(pl.LightningModule):
|
|
| 82 |
norm_preds_squeezed, sxr, sxr_un
|
| 83 |
)
|
| 84 |
|
| 85 |
-
#Also calculate huber loss for logging
|
| 86 |
huber_loss = F.huber_loss(norm_preds_squeezed, sxr, delta=.3)
|
| 87 |
mse_loss = F.mse_loss(norm_preds_squeezed, sxr)
|
| 88 |
mae_loss = F.l1_loss(norm_preds_squeezed, sxr)
|
|
@@ -116,10 +114,12 @@ class ViTLocal(pl.LightningModule):
|
|
| 116 |
for key, value in multipliers.items():
|
| 117 |
self.log(f"val/adaptive/{key}", value, on_step=False, on_epoch=True)
|
| 118 |
self.log("val_total_loss", loss, on_step=False, on_epoch=True, prog_bar=True, logger=True, sync_dist=True)
|
| 119 |
-
self.log("val_huber_loss", huber_loss, on_step=False, on_epoch=True, prog_bar=True, logger=True,
|
|
|
|
| 120 |
self.log("val_mse_loss", mse_loss, on_step=False, on_epoch=True, prog_bar=True, logger=True, sync_dist=True)
|
| 121 |
self.log("val_mae_loss", mae_loss, on_step=False, on_epoch=True, prog_bar=True, logger=True, sync_dist=True)
|
| 122 |
-
self.log("val_rmse_loss", rmse_loss, on_step=False, on_epoch=True, prog_bar=True, logger=True,
|
|
|
|
| 123 |
|
| 124 |
return loss
|
| 125 |
|
|
@@ -133,7 +133,6 @@ class ViTLocal(pl.LightningModule):
|
|
| 133 |
self._calculate_loss(batch, mode="test")
|
| 134 |
|
| 135 |
|
| 136 |
-
|
| 137 |
class VisionTransformerLocal(nn.Module):
|
| 138 |
def __init__(
|
| 139 |
self,
|
|
@@ -170,7 +169,7 @@ class VisionTransformerLocal(nn.Module):
|
|
| 170 |
self.input_layer = nn.Linear(num_channels * (patch_size ** 2), embed_dim)
|
| 171 |
|
| 172 |
self.transformer_blocks = nn.ModuleList([
|
| 173 |
-
|
| 174 |
for _ in range(num_layers)
|
| 175 |
])
|
| 176 |
|
|
@@ -183,7 +182,6 @@ class VisionTransformerLocal(nn.Module):
|
|
| 183 |
self.grid_w = int(math.sqrt(num_patches))
|
| 184 |
self.pos_embedding_2d = nn.Parameter(torch.randn(1, self.grid_h, self.grid_w, embed_dim))
|
| 185 |
|
| 186 |
-
|
| 187 |
def forward(self, x, sxr_norm, return_attention=False):
|
| 188 |
# Preprocess input
|
| 189 |
x = img_to_patch(x, self.patch_size)
|
|
@@ -199,35 +197,22 @@ class VisionTransformerLocal(nn.Module):
|
|
| 199 |
|
| 200 |
attention_weights = []
|
| 201 |
for block in self.transformer_blocks:
|
| 202 |
-
if
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
x, attn_weights = torch.utils.checkpoint.checkpoint(
|
| 206 |
-
block, x, return_attention, use_reentrant=False
|
| 207 |
-
)
|
| 208 |
-
attention_weights.append(attn_weights)
|
| 209 |
-
else:
|
| 210 |
-
x = torch.utils.checkpoint.checkpoint(
|
| 211 |
-
block, x, return_attention, use_reentrant=False
|
| 212 |
-
)
|
| 213 |
else:
|
| 214 |
-
|
| 215 |
-
if return_attention:
|
| 216 |
-
x, attn_weights = block(x, return_attention=True)
|
| 217 |
-
attention_weights.append(attn_weights)
|
| 218 |
-
else:
|
| 219 |
-
x = block(x)
|
| 220 |
|
| 221 |
patch_embeddings = x.transpose(0, 1) # [B, num_patches, embed_dim]
|
| 222 |
patch_logits = self.mlp_head(patch_embeddings).squeeze(-1) # normalized log predictions [B, num_patches]
|
| 223 |
|
| 224 |
# --- Convert to raw SXR ---
|
| 225 |
mean, std = sxr_norm # in log10 space
|
| 226 |
-
patch_flux_raw = torch.clamp(10 ** (patch_logits * std + mean)- 1e-8, min=1e-15, max=1)
|
| 227 |
|
| 228 |
# Sum over patches for raw global flux
|
| 229 |
global_flux_raw = patch_flux_raw.sum(dim=1, keepdim=True)
|
| 230 |
-
|
| 231 |
# Ensure global flux is never zero (add small epsilon if needed)
|
| 232 |
global_flux_raw = torch.clamp(global_flux_raw, min=1e-15)
|
| 233 |
|
|
@@ -235,29 +220,29 @@ class VisionTransformerLocal(nn.Module):
|
|
| 235 |
return global_flux_raw, attention_weights, patch_flux_raw
|
| 236 |
else:
|
| 237 |
return global_flux_raw, patch_flux_raw
|
| 238 |
-
|
| 239 |
def _add_2d_positional_encoding(self, x):
|
| 240 |
"""Add learned 2D positional encoding to patch embeddings"""
|
| 241 |
B, T, embed_dim = x.shape
|
| 242 |
num_patches = T # All tokens are patches (no CLS token)
|
| 243 |
-
|
| 244 |
# Reshape patches to 2D grid: [B, grid_h, grid_w, embed_dim]
|
| 245 |
patch_embeddings = x.reshape(B, self.grid_h, self.grid_w, embed_dim)
|
| 246 |
-
|
| 247 |
# Add learned 2D positional encoding
|
| 248 |
# Broadcasting: [B, grid_h, grid_w, embed_dim] + [1, grid_h, grid_w, embed_dim]
|
| 249 |
patch_embeddings = patch_embeddings + self.pos_embedding_2d
|
| 250 |
-
|
| 251 |
# Reshape back to sequence format: [B, num_patches, embed_dim]
|
| 252 |
x = patch_embeddings.reshape(B, num_patches, embed_dim)
|
| 253 |
-
|
| 254 |
return x
|
| 255 |
-
|
| 256 |
def forward_for_callback(self, x, return_attention=True):
|
| 257 |
"""Forward method compatible with AttentionMapCallback"""
|
| 258 |
global_flux_raw, attention_weights, patch_flux_raw = self.forward(x, return_attention=return_attention)
|
| 259 |
# Callback expects (outputs, attention_weights, _)
|
| 260 |
-
return global_flux_raw, attention_weights
|
| 261 |
|
| 262 |
|
| 263 |
class AttentionBlock(nn.Module):
|
|
@@ -300,7 +285,7 @@ class AttentionBlock(nn.Module):
|
|
| 300 |
return x
|
| 301 |
|
| 302 |
|
| 303 |
-
class
|
| 304 |
def __init__(self, embed_dim, hidden_dim, num_heads, num_patches, dropout=0.0, local_window=9):
|
| 305 |
super().__init__()
|
| 306 |
self.embed_dim = embed_dim
|
|
@@ -317,36 +302,38 @@ class LocalAttentionBlock(nn.Module):
|
|
| 317 |
nn.Linear(hidden_dim, embed_dim),
|
| 318 |
nn.Dropout(dropout),
|
| 319 |
)
|
| 320 |
-
|
| 321 |
# Pre-compute attention mask for local interactions
|
| 322 |
self.register_buffer('attention_mask', self._create_local_attention_mask())
|
| 323 |
|
| 324 |
def _create_local_attention_mask(self):
|
| 325 |
"""Create attention mask for local interactions only"""
|
| 326 |
-
# This creates a mask where only
|
| 327 |
-
|
| 328 |
-
# attend to patches within a 3x3 window around it
|
| 329 |
-
|
| 330 |
num_patches = self.num_patches
|
| 331 |
grid_size = int(math.sqrt(num_patches))
|
| 332 |
-
half_w = self.local_window // 2
|
| 333 |
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
cols = indices % grid_size
|
| 337 |
-
row_dist = torch.abs(rows.unsqueeze(1) - rows.unsqueeze(0))
|
| 338 |
-
col_dist = torch.abs(cols.unsqueeze(1) - cols.unsqueeze(0))
|
| 339 |
-
mask = (row_dist <= half_w) & (col_dist <= half_w)
|
| 340 |
|
| 341 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
|
| 343 |
def forward(self, x, return_attention=False):
|
| 344 |
inp_x = self.layer_norm_1(x)
|
| 345 |
-
|
| 346 |
if return_attention:
|
| 347 |
# Apply local attention mask
|
| 348 |
attn_output, attn_weights = self.attn(
|
| 349 |
-
inp_x, inp_x, inp_x,
|
| 350 |
attn_mask=self.attention_mask,
|
| 351 |
average_attn_weights=False
|
| 352 |
)
|
|
@@ -362,6 +349,7 @@ class LocalAttentionBlock(nn.Module):
|
|
| 362 |
x = x + self.linear(self.layer_norm_2(x))
|
| 363 |
return x
|
| 364 |
|
|
|
|
| 365 |
def img_to_patch(x, patch_size, flatten_channels=True):
|
| 366 |
"""
|
| 367 |
Args:
|
|
@@ -379,8 +367,9 @@ def img_to_patch(x, patch_size, flatten_channels=True):
|
|
| 379 |
x = x.flatten(2, 4) # [B, H'*W', C*p_H*p_W]
|
| 380 |
return x
|
| 381 |
|
|
|
|
| 382 |
class SXRRegressionDynamicLoss:
|
| 383 |
-
def __init__(self, window_size=15000, base_weights=None):
|
| 384 |
self.c_threshold = 1e-6
|
| 385 |
self.m_threshold = 1e-5
|
| 386 |
self.x_threshold = 1e-4
|
|
@@ -391,14 +380,14 @@ class SXRRegressionDynamicLoss:
|
|
| 391 |
self.m_errors = deque(maxlen=window_size)
|
| 392 |
self.x_errors = deque(maxlen=window_size)
|
| 393 |
|
| 394 |
-
#Calculate the base weights based on the number of samples in each class within training data
|
| 395 |
if base_weights is None:
|
| 396 |
self.base_weights = self._get_base_weights()
|
| 397 |
else:
|
| 398 |
self.base_weights = base_weights
|
| 399 |
|
| 400 |
def _get_base_weights(self):
|
| 401 |
-
#
|
| 402 |
return {
|
| 403 |
'quiet': 6.643528005464481, # Increase from current value
|
| 404 |
'c_class': 1.626986450317832, # Keep as baseline
|
|
@@ -408,7 +397,7 @@ class SXRRegressionDynamicLoss:
|
|
| 408 |
|
| 409 |
def calculate_loss(self, preds_norm, sxr_norm, sxr_un):
|
| 410 |
base_loss = F.huber_loss(preds_norm, sxr_norm, delta=.3, reduction='none')
|
| 411 |
-
#base_loss = F.mse_loss(preds_norm, sxr_norm, reduction='none')
|
| 412 |
weights = self._get_adaptive_weights(sxr_un)
|
| 413 |
self._update_tracking(sxr_un, sxr_norm, preds_norm)
|
| 414 |
weighted_loss = base_loss * weights
|
|
@@ -423,10 +412,10 @@ class SXRRegressionDynamicLoss:
|
|
| 423 |
self.quiet_errors, max_multiplier=1.5, min_multiplier=0.6, sensitivity=0.05, sxrclass='quiet' # Was 0.2
|
| 424 |
)
|
| 425 |
c_mult = self._get_performance_multiplier(
|
| 426 |
-
self.c_errors, max_multiplier=2, min_multiplier=0.7, sensitivity=0.08, sxrclass='c_class'
|
| 427 |
)
|
| 428 |
m_mult = self._get_performance_multiplier(
|
| 429 |
-
self.m_errors, max_multiplier=5.0, min_multiplier=0.8, sensitivity=0.1, sxrclass='m_class'
|
| 430 |
)
|
| 431 |
x_mult = self._get_performance_multiplier(
|
| 432 |
self.x_errors, max_multiplier=8.0, min_multiplier=0.8, sensitivity=0.12, sxrclass='x_class' # Was 0.5
|
|
@@ -461,7 +450,8 @@ class SXRRegressionDynamicLoss:
|
|
| 461 |
|
| 462 |
return weights
|
| 463 |
|
| 464 |
-
def _get_performance_multiplier(self, error_history, max_multiplier=10.0, min_multiplier=0.5, sensitivity=3.0,
|
|
|
|
| 465 |
"""Class-dependent performance multiplier"""
|
| 466 |
|
| 467 |
class_params = {
|
|
@@ -482,15 +472,13 @@ class SXRRegressionDynamicLoss:
|
|
| 482 |
multiplier = np.exp(sensitivity * (ratio - 1))
|
| 483 |
return np.clip(multiplier, min_multiplier, max_multiplier)
|
| 484 |
|
| 485 |
-
|
| 486 |
def _update_tracking(self, sxr_un, sxr_norm, preds_norm):
|
| 487 |
sxr_un_np = sxr_un.detach().cpu().numpy()
|
| 488 |
|
| 489 |
-
#Huber loss
|
| 490 |
error = F.huber_loss(preds_norm, sxr_norm, delta=.3, reduction='none')
|
| 491 |
error = error.detach().cpu().numpy()
|
| 492 |
|
| 493 |
-
|
| 494 |
quiet_mask = sxr_un_np < self.c_threshold
|
| 495 |
if quiet_mask.sum() > 0:
|
| 496 |
self.quiet_errors.append(float(np.mean(error[quiet_mask])))
|
|
@@ -507,7 +495,6 @@ class SXRRegressionDynamicLoss:
|
|
| 507 |
if x_mask.sum() > 0:
|
| 508 |
self.x_errors.append(float(np.mean(error[x_mask])))
|
| 509 |
|
| 510 |
-
|
| 511 |
def get_current_multipliers(self):
|
| 512 |
"""Get current performance multipliers for logging"""
|
| 513 |
return {
|
|
|
|
| 5 |
import torch
|
| 6 |
import torch.nn as nn
|
| 7 |
import torch.nn.functional as F
|
|
|
|
| 8 |
import pytorch_lightning as pl
|
| 9 |
from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts
|
| 10 |
|
|
|
|
| 11 |
|
| 12 |
def normalize_sxr(unnormalized_values, sxr_norm):
|
| 13 |
"""Convert from unnormalized to normalized space"""
|
|
|
|
| 15 |
normalized = (log_values - float(sxr_norm[0].item())) / float(sxr_norm[1].item())
|
| 16 |
return normalized
|
| 17 |
|
| 18 |
+
|
| 19 |
def unnormalize_sxr(normalized_values, sxr_norm):
|
| 20 |
return 10 ** (normalized_values * float(sxr_norm[1].item()) + float(sxr_norm[0].item())) - 1e-8
|
| 21 |
|
| 22 |
+
|
| 23 |
class ViTLocal(pl.LightningModule):
|
| 24 |
def __init__(self, model_kwargs, sxr_norm, base_weights=None):
|
| 25 |
super().__init__()
|
|
|
|
| 30 |
filtered_kwargs.pop('lr', None)
|
| 31 |
filtered_kwargs.pop('num_classes', None)
|
| 32 |
self.model = VisionTransformerLocal(**filtered_kwargs)
|
| 33 |
+
# Set the base weights based on the number of samples in each class within training data
|
| 34 |
self.base_weights = base_weights
|
| 35 |
self.adaptive_loss = SXRRegressionDynamicLoss(window_size=15000, base_weights=self.base_weights)
|
| 36 |
self.sxr_norm = sxr_norm
|
|
|
|
|
|
|
| 37 |
|
| 38 |
def forward(self, x, return_attention=True):
|
| 39 |
return self.model(x, self.sxr_norm, return_attention=return_attention)
|
|
|
|
| 70 |
|
| 71 |
def _calculate_loss(self, batch, mode="train"):
|
| 72 |
imgs, sxr = batch
|
| 73 |
+
raw_preds, raw_patch_contributions = self.model(imgs, self.sxr_norm)
|
| 74 |
raw_preds_squeezed = torch.squeeze(raw_preds)
|
| 75 |
sxr_un = unnormalize_sxr(sxr, self.sxr_norm)
|
| 76 |
|
|
|
|
| 80 |
norm_preds_squeezed, sxr, sxr_un
|
| 81 |
)
|
| 82 |
|
| 83 |
+
# Also calculate huber loss for logging
|
| 84 |
huber_loss = F.huber_loss(norm_preds_squeezed, sxr, delta=.3)
|
| 85 |
mse_loss = F.mse_loss(norm_preds_squeezed, sxr)
|
| 86 |
mae_loss = F.l1_loss(norm_preds_squeezed, sxr)
|
|
|
|
| 114 |
for key, value in multipliers.items():
|
| 115 |
self.log(f"val/adaptive/{key}", value, on_step=False, on_epoch=True)
|
| 116 |
self.log("val_total_loss", loss, on_step=False, on_epoch=True, prog_bar=True, logger=True, sync_dist=True)
|
| 117 |
+
self.log("val_huber_loss", huber_loss, on_step=False, on_epoch=True, prog_bar=True, logger=True,
|
| 118 |
+
sync_dist=True)
|
| 119 |
self.log("val_mse_loss", mse_loss, on_step=False, on_epoch=True, prog_bar=True, logger=True, sync_dist=True)
|
| 120 |
self.log("val_mae_loss", mae_loss, on_step=False, on_epoch=True, prog_bar=True, logger=True, sync_dist=True)
|
| 121 |
+
self.log("val_rmse_loss", rmse_loss, on_step=False, on_epoch=True, prog_bar=True, logger=True,
|
| 122 |
+
sync_dist=True)
|
| 123 |
|
| 124 |
return loss
|
| 125 |
|
|
|
|
| 133 |
self._calculate_loss(batch, mode="test")
|
| 134 |
|
| 135 |
|
|
|
|
| 136 |
class VisionTransformerLocal(nn.Module):
|
| 137 |
def __init__(
|
| 138 |
self,
|
|
|
|
| 169 |
self.input_layer = nn.Linear(num_channels * (patch_size ** 2), embed_dim)
|
| 170 |
|
| 171 |
self.transformer_blocks = nn.ModuleList([
|
| 172 |
+
InvertedAttentionBlock(embed_dim, hidden_dim, num_heads, num_patches, dropout=dropout)
|
| 173 |
for _ in range(num_layers)
|
| 174 |
])
|
| 175 |
|
|
|
|
| 182 |
self.grid_w = int(math.sqrt(num_patches))
|
| 183 |
self.pos_embedding_2d = nn.Parameter(torch.randn(1, self.grid_h, self.grid_w, embed_dim))
|
| 184 |
|
|
|
|
| 185 |
def forward(self, x, sxr_norm, return_attention=False):
|
| 186 |
# Preprocess input
|
| 187 |
x = img_to_patch(x, self.patch_size)
|
|
|
|
| 197 |
|
| 198 |
attention_weights = []
|
| 199 |
for block in self.transformer_blocks:
|
| 200 |
+
if return_attention:
|
| 201 |
+
x, attn_weights = block(x, return_attention=True)
|
| 202 |
+
attention_weights.append(attn_weights)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
else:
|
| 204 |
+
x = block(x)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
|
| 206 |
patch_embeddings = x.transpose(0, 1) # [B, num_patches, embed_dim]
|
| 207 |
patch_logits = self.mlp_head(patch_embeddings).squeeze(-1) # normalized log predictions [B, num_patches]
|
| 208 |
|
| 209 |
# --- Convert to raw SXR ---
|
| 210 |
mean, std = sxr_norm # in log10 space
|
| 211 |
+
patch_flux_raw = torch.clamp(10 ** (patch_logits * std + mean) - 1e-8, min=1e-15, max=1)
|
| 212 |
|
| 213 |
# Sum over patches for raw global flux
|
| 214 |
global_flux_raw = patch_flux_raw.sum(dim=1, keepdim=True)
|
| 215 |
+
|
| 216 |
# Ensure global flux is never zero (add small epsilon if needed)
|
| 217 |
global_flux_raw = torch.clamp(global_flux_raw, min=1e-15)
|
| 218 |
|
|
|
|
| 220 |
return global_flux_raw, attention_weights, patch_flux_raw
|
| 221 |
else:
|
| 222 |
return global_flux_raw, patch_flux_raw
|
| 223 |
+
|
| 224 |
def _add_2d_positional_encoding(self, x):
|
| 225 |
"""Add learned 2D positional encoding to patch embeddings"""
|
| 226 |
B, T, embed_dim = x.shape
|
| 227 |
num_patches = T # All tokens are patches (no CLS token)
|
| 228 |
+
|
| 229 |
# Reshape patches to 2D grid: [B, grid_h, grid_w, embed_dim]
|
| 230 |
patch_embeddings = x.reshape(B, self.grid_h, self.grid_w, embed_dim)
|
| 231 |
+
|
| 232 |
# Add learned 2D positional encoding
|
| 233 |
# Broadcasting: [B, grid_h, grid_w, embed_dim] + [1, grid_h, grid_w, embed_dim]
|
| 234 |
patch_embeddings = patch_embeddings + self.pos_embedding_2d
|
| 235 |
+
|
| 236 |
# Reshape back to sequence format: [B, num_patches, embed_dim]
|
| 237 |
x = patch_embeddings.reshape(B, num_patches, embed_dim)
|
| 238 |
+
|
| 239 |
return x
|
| 240 |
+
|
| 241 |
def forward_for_callback(self, x, return_attention=True):
|
| 242 |
"""Forward method compatible with AttentionMapCallback"""
|
| 243 |
global_flux_raw, attention_weights, patch_flux_raw = self.forward(x, return_attention=return_attention)
|
| 244 |
# Callback expects (outputs, attention_weights, _)
|
| 245 |
+
return global_flux_raw, attention_weights
|
| 246 |
|
| 247 |
|
| 248 |
class AttentionBlock(nn.Module):
|
|
|
|
| 285 |
return x
|
| 286 |
|
| 287 |
|
| 288 |
+
class InvertedAttentionBlock(nn.Module):
|
| 289 |
def __init__(self, embed_dim, hidden_dim, num_heads, num_patches, dropout=0.0, local_window=9):
|
| 290 |
super().__init__()
|
| 291 |
self.embed_dim = embed_dim
|
|
|
|
| 302 |
nn.Linear(hidden_dim, embed_dim),
|
| 303 |
nn.Dropout(dropout),
|
| 304 |
)
|
| 305 |
+
|
| 306 |
# Pre-compute attention mask for local interactions
|
| 307 |
self.register_buffer('attention_mask', self._create_local_attention_mask())
|
| 308 |
|
| 309 |
def _create_local_attention_mask(self):
|
| 310 |
"""Create attention mask for local interactions only"""
|
| 311 |
+
# This creates a mask where only distant patches can attend to each other
|
| 312 |
+
|
|
|
|
|
|
|
| 313 |
num_patches = self.num_patches
|
| 314 |
grid_size = int(math.sqrt(num_patches))
|
|
|
|
| 315 |
|
| 316 |
+
# Create mask for patches only: [num_patches, num_patches]
|
| 317 |
+
mask = torch.zeros(num_patches, num_patches)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
|
| 319 |
+
# Patches can only attend to nearby patches
|
| 320 |
+
for i in range(num_patches):
|
| 321 |
+
row_i, col_i = i // grid_size, i % grid_size
|
| 322 |
+
for j in range(num_patches):
|
| 323 |
+
row_j, col_j = j // grid_size, j % grid_size
|
| 324 |
+
# Only allow attention if patches are within local_window distance
|
| 325 |
+
if abs(row_i - row_j) <= self.local_window // 2 and abs(col_i - col_j) <= self.local_window // 2:
|
| 326 |
+
mask[i, j] = 1
|
| 327 |
+
|
| 328 |
+
return mask.bool()
|
| 329 |
|
| 330 |
def forward(self, x, return_attention=False):
|
| 331 |
inp_x = self.layer_norm_1(x)
|
| 332 |
+
|
| 333 |
if return_attention:
|
| 334 |
# Apply local attention mask
|
| 335 |
attn_output, attn_weights = self.attn(
|
| 336 |
+
inp_x, inp_x, inp_x,
|
| 337 |
attn_mask=self.attention_mask,
|
| 338 |
average_attn_weights=False
|
| 339 |
)
|
|
|
|
| 349 |
x = x + self.linear(self.layer_norm_2(x))
|
| 350 |
return x
|
| 351 |
|
| 352 |
+
|
| 353 |
def img_to_patch(x, patch_size, flatten_channels=True):
|
| 354 |
"""
|
| 355 |
Args:
|
|
|
|
| 367 |
x = x.flatten(2, 4) # [B, H'*W', C*p_H*p_W]
|
| 368 |
return x
|
| 369 |
|
| 370 |
+
|
| 371 |
class SXRRegressionDynamicLoss:
|
| 372 |
+
def __init__(self, window_size=15000, base_weights=None):
|
| 373 |
self.c_threshold = 1e-6
|
| 374 |
self.m_threshold = 1e-5
|
| 375 |
self.x_threshold = 1e-4
|
|
|
|
| 380 |
self.m_errors = deque(maxlen=window_size)
|
| 381 |
self.x_errors = deque(maxlen=window_size)
|
| 382 |
|
| 383 |
+
# Calculate the base weights based on the number of samples in each class within training data
|
| 384 |
if base_weights is None:
|
| 385 |
self.base_weights = self._get_base_weights()
|
| 386 |
else:
|
| 387 |
self.base_weights = base_weights
|
| 388 |
|
| 389 |
def _get_base_weights(self):
|
| 390 |
+
# Base weights based on the number of samples in each class within training data
|
| 391 |
return {
|
| 392 |
'quiet': 6.643528005464481, # Increase from current value
|
| 393 |
'c_class': 1.626986450317832, # Keep as baseline
|
|
|
|
| 397 |
|
| 398 |
def calculate_loss(self, preds_norm, sxr_norm, sxr_un):
|
| 399 |
base_loss = F.huber_loss(preds_norm, sxr_norm, delta=.3, reduction='none')
|
| 400 |
+
# base_loss = F.mse_loss(preds_norm, sxr_norm, reduction='none')
|
| 401 |
weights = self._get_adaptive_weights(sxr_un)
|
| 402 |
self._update_tracking(sxr_un, sxr_norm, preds_norm)
|
| 403 |
weighted_loss = base_loss * weights
|
|
|
|
| 412 |
self.quiet_errors, max_multiplier=1.5, min_multiplier=0.6, sensitivity=0.05, sxrclass='quiet' # Was 0.2
|
| 413 |
)
|
| 414 |
c_mult = self._get_performance_multiplier(
|
| 415 |
+
self.c_errors, max_multiplier=2, min_multiplier=0.7, sensitivity=0.08, sxrclass='c_class' # Was 0.3
|
| 416 |
)
|
| 417 |
m_mult = self._get_performance_multiplier(
|
| 418 |
+
self.m_errors, max_multiplier=5.0, min_multiplier=0.8, sensitivity=0.1, sxrclass='m_class' # Was 0.4
|
| 419 |
)
|
| 420 |
x_mult = self._get_performance_multiplier(
|
| 421 |
self.x_errors, max_multiplier=8.0, min_multiplier=0.8, sensitivity=0.12, sxrclass='x_class' # Was 0.5
|
|
|
|
| 450 |
|
| 451 |
return weights
|
| 452 |
|
| 453 |
+
def _get_performance_multiplier(self, error_history, max_multiplier=10.0, min_multiplier=0.5, sensitivity=3.0,
|
| 454 |
+
sxrclass='quiet'):
|
| 455 |
"""Class-dependent performance multiplier"""
|
| 456 |
|
| 457 |
class_params = {
|
|
|
|
| 472 |
multiplier = np.exp(sensitivity * (ratio - 1))
|
| 473 |
return np.clip(multiplier, min_multiplier, max_multiplier)
|
| 474 |
|
|
|
|
| 475 |
def _update_tracking(self, sxr_un, sxr_norm, preds_norm):
|
| 476 |
sxr_un_np = sxr_un.detach().cpu().numpy()
|
| 477 |
|
| 478 |
+
# Huber loss
|
| 479 |
error = F.huber_loss(preds_norm, sxr_norm, delta=.3, reduction='none')
|
| 480 |
error = error.detach().cpu().numpy()
|
| 481 |
|
|
|
|
| 482 |
quiet_mask = sxr_un_np < self.c_threshold
|
| 483 |
if quiet_mask.sum() > 0:
|
| 484 |
self.quiet_errors.append(float(np.mean(error[quiet_mask])))
|
|
|
|
| 495 |
if x_mask.sum() > 0:
|
| 496 |
self.x_errors.append(float(np.mean(error[x_mask])))
|
| 497 |
|
|
|
|
| 498 |
def get_current_multipliers(self):
|
| 499 |
"""Get current performance multipliers for logging"""
|
| 500 |
return {
|