mattbitzesty commited on
Commit
9ddcf86
·
unverified ·
1 Parent(s): 31f09ab

fix(loss): prevent objective-starvation with fixed task weights; target pimt_v3.pt

Browse files
scripts/hf_train_job.py CHANGED
@@ -122,7 +122,7 @@ def hf_train_5epoch() -> None:
122
  api = HfApi(token=token)
123
  api.upload_file(
124
  path_or_fileobj=str(checkpoint_path),
125
- path_in_repo="pimt_v2.pt",
126
  repo_id=repo_id,
127
  repo_type="model",
128
  )
 
122
  api = HfApi(token=token)
123
  api.upload_file(
124
  path_or_fileobj=str(checkpoint_path),
125
+ path_in_repo="pimt_v3.pt",
126
  repo_id=repo_id,
127
  repo_type="model",
128
  )
scripts/predict_shalimar.py CHANGED
@@ -218,11 +218,11 @@ def build_model_inputs(
218
 
219
 
220
  def load_pimt_checkpoint() -> tuple[PhysicsInformedMixtureTransformer, PIMTHeads, torch.device]:
221
- checkpoint_path = Path("models/pimt_v1.pt")
222
  if not checkpoint_path.exists():
223
  hf_hub_download(
224
  repo_id="mattbitzesty/pino-pimt-checkpoint",
225
- filename="pimt_v1.pt",
226
  repo_type="model",
227
  local_dir="models",
228
  )
 
218
 
219
 
220
  def load_pimt_checkpoint() -> tuple[PhysicsInformedMixtureTransformer, PIMTHeads, torch.device]:
221
+ checkpoint_path = Path("models/pimt_v3.pt")
222
  if not checkpoint_path.exists():
223
  hf_hub_download(
224
  repo_id="mattbitzesty/pino-pimt-checkpoint",
225
+ filename="pimt_v3.pt",
226
  repo_type="model",
227
  local_dir="models",
228
  )
src/pino/thermo/losses.py CHANGED
@@ -4,32 +4,56 @@ import torch.nn as nn
4
 
5
  class AdaptiveLossBalancer(nn.Module):
6
  """
7
- Adaptive multi-task loss balancer.
8
 
9
- Tracks the running magnitudes of each task loss relative to their initial
10
- baselines and rescales gradients by inverse progress ratios, eliminating the
11
- need for hand-tuned task weights.
 
 
 
 
 
 
 
 
12
  """
13
 
14
- def __init__(self, num_tasks: int = 4, momentum: float = 0.9) -> None:
 
 
 
 
 
 
15
  super().__init__()
16
  self.momentum = momentum
 
17
  self.register_buffer("running_losses", torch.ones(num_tasks))
18
  self.register_buffer("initial_losses", torch.zeros(num_tasks))
19
  self.register_buffer("_initialized", torch.tensor(0, dtype=torch.bool))
 
 
 
 
 
 
 
 
 
 
20
 
21
  def forward(self, loss_dict: dict[str, torch.Tensor]) -> torch.Tensor:
22
- """
23
- Balances losses based on their progress relative to initial baselines.
24
-
25
- Tasks that improve more slowly receive higher weights, preventing a single
26
- task from dominating the backward pass.
27
-
28
- The computed weights are stored in ``self.last_weights`` as a detached
29
- CPU list so training loops can log them without modifying the loss flow.
30
- """
31
  losses = torch.stack(list(loss_dict.values()))
 
32
 
 
 
 
 
 
 
33
  if not self._initialized.item() or torch.all(self.initial_losses == 0):
34
  self.initial_losses.copy_(losses.detach().clamp(min=1e-5))
35
  self.running_losses.copy_(losses.detach().clamp(min=1e-5))
@@ -41,8 +65,10 @@ class AdaptiveLossBalancer(nn.Module):
41
 
42
  ratios = self.running_losses / self.initial_losses
43
  weights = ratios / (torch.sum(ratios) + 1e-8)
44
- total_loss = torch.sum(losses * weights * float(len(losses)))
45
 
46
- self.last_weights = weights.detach().cpu().tolist()
 
 
47
 
48
- return total_loss
 
 
4
 
5
  class AdaptiveLossBalancer(nn.Module):
6
  """
7
+ Multi-task loss weighting with optional adaptive floor.
8
 
9
+ Two modes:
10
+ * ``fixed_weights``: directly supplied task weights (e.g., priority weighting
11
+ for the time-resolved objective head). This is the default in PINO because
12
+ the objective head is the only task that consumes the physics trajectory;
13
+ letting it be starved removes the model's ability to learn time dynamics.
14
+ * ``adaptive`` mode: weights are derived from per-task progress ratios
15
+ (current / initial loss) with a per-task floor so that fast-converging
16
+ tasks are not dropped to zero.
17
+
18
+ The computed weights are stored in ``self.last_weights`` as a detached CPU list
19
+ so training loops can log them without modifying the loss flow.
20
  """
21
 
22
+ def __init__(
23
+ self,
24
+ num_tasks: int = 4,
25
+ fixed_weights: torch.Tensor | None = None,
26
+ momentum: float = 0.9,
27
+ min_weight: float = 0.20,
28
+ ) -> None:
29
  super().__init__()
30
  self.momentum = momentum
31
+ self.min_weight = min_weight
32
  self.register_buffer("running_losses", torch.ones(num_tasks))
33
  self.register_buffer("initial_losses", torch.zeros(num_tasks))
34
  self.register_buffer("_initialized", torch.tensor(0, dtype=torch.bool))
35
+ if fixed_weights is not None:
36
+ fixed = torch.as_tensor(fixed_weights, dtype=torch.float32)
37
+ if fixed.dim() == 1 and fixed.numel() == num_tasks:
38
+ self.register_buffer("fixed_weights", fixed)
39
+ else:
40
+ raise ValueError(
41
+ f"fixed_weights must be a {num_tasks}-element vector, got shape {fixed.shape}"
42
+ )
43
+ else:
44
+ self.register_buffer("fixed_weights", torch.zeros(num_tasks))
45
 
46
  def forward(self, loss_dict: dict[str, torch.Tensor]) -> torch.Tensor:
47
+ """Combine task losses with either fixed or adaptive weights."""
 
 
 
 
 
 
 
 
48
  losses = torch.stack(list(loss_dict.values()))
49
+ num_tasks = float(len(losses))
50
 
51
+ if self.fixed_weights.abs().sum().item() > 0:
52
+ weights = self.fixed_weights.to(losses.device)
53
+ self.last_weights = weights.detach().cpu().tolist()
54
+ return torch.sum(losses * weights)
55
+
56
+ # Adaptive fallback.
57
  if not self._initialized.item() or torch.all(self.initial_losses == 0):
58
  self.initial_losses.copy_(losses.detach().clamp(min=1e-5))
59
  self.running_losses.copy_(losses.detach().clamp(min=1e-5))
 
65
 
66
  ratios = self.running_losses / self.initial_losses
67
  weights = ratios / (torch.sum(ratios) + 1e-8)
 
68
 
69
+ # Apply a floor so that fast-converging tasks are not starved.
70
+ weights = torch.clamp(weights, min=self.min_weight) # type: ignore[attr-defined]
71
+ weights = weights / (torch.sum(weights) + 1e-8) # type: ignore[attr-defined]
72
 
73
+ self.last_weights = weights.detach().cpu().tolist()
74
+ return torch.sum(losses * weights * num_tasks)
src/pino/train.py CHANGED
@@ -266,7 +266,7 @@ def main():
266
  "max_batches_per_epoch": None,
267
  "lr": args.lr,
268
  "weight_decay": 1e-2,
269
- "checkpoint_name": "pimt_v2.pt",
270
  }
271
  logger.info("Configuration: %s", cfg)
272
 
@@ -339,8 +339,13 @@ def main():
339
  optimizer = optim.AdamW(params, lr=cfg["lr"], weight_decay=cfg["weight_decay"])
340
  scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs)
341
 
342
- # Adaptive multi-task loss balancer (DeepSeek-style inverse-progress-ratio weighting).
343
- loss_balancer = AdaptiveLossBalancer(num_tasks=4).to(device)
 
 
 
 
 
344
 
345
  writer = SummaryWriter(log_dir=args.log_dir)
346
  output_dir = Path(args.output_dir)
 
266
  "max_batches_per_epoch": None,
267
  "lr": args.lr,
268
  "weight_decay": 1e-2,
269
+ "checkpoint_name": "pimt_v3.pt",
270
  }
271
  logger.info("Configuration: %s", cfg)
272
 
 
339
  optimizer = optim.AdamW(params, lr=cfg["lr"], weight_decay=cfg["weight_decay"])
340
  scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs)
341
 
342
+ # Multi-task loss balancer. We fix the objective weight high because it is
343
+ # the only time-resolved head; letting the balancer starve it to ~0.01% causes
344
+ # the model to collapse to a static baseline.
345
+ loss_weights = torch.tensor([0.45, 0.15, 0.15, 0.25])
346
+ loss_balancer = AdaptiveLossBalancer(
347
+ num_tasks=4, fixed_weights=loss_weights
348
+ ).to(device)
349
 
350
  writer = SummaryWriter(log_dir=args.log_dir)
351
  output_dir = Path(args.output_dir)