mattbitzesty commited on
Commit
254d9db
·
unverified ·
1 Parent(s): 05cb1f2

feat(train,heads,loss): DeepSeekLossBalancer + continuous cosine alignment

Browse files

- Replace InfoNCE contrastive head with ContinuousAlignmentHead (138-D sigmoid).
- Add DeepSeekLossBalancer for adaptive 4-task loss weighting (obj/season/wear/alignment).
- Wire balancer into train.py; remove manual weights and info_nce_loss.
- Update evaluate.py to extract alignment embeddings instead of contrastive.
- Update pimt_model_hf.py to emit alignment logits and 283-D fused labels.
- Scale train_hf.py collator tokens to 145-D.

src/pino/evaluate.py CHANGED
@@ -82,7 +82,7 @@ def extract_embeddings(
82
  target_obj = batch["target_obj"].to(device)
83
  latent = model(tokens, physics, src_key_padding_mask)
84
  pred = heads(latent)
85
- z = pred["contrastive"].cpu().numpy()
86
  # Mean-pool objective trajectory over time for a single perceptual vector.
87
  y = target_obj.mean(dim=1).cpu().numpy()
88
  embeddings.append(z)
 
82
  target_obj = batch["target_obj"].to(device)
83
  latent = model(tokens, physics, src_key_padding_mask)
84
  pred = heads(latent)
85
+ z = pred["alignment"].cpu().numpy()
86
  # Mean-pool objective trajectory over time for a single perceptual vector.
87
  y = target_obj.mean(dim=1).cpu().numpy()
88
  embeddings.append(z)
src/pino/heads.py CHANGED
@@ -65,55 +65,57 @@ class SubjectiveSemanticHead(nn.Module):
65
  }
66
 
67
 
68
- class ContrastiveProjectionHead(nn.Module):
69
  """
70
- Projection head for the perceptual contrastive loss.
71
 
72
- Mean-pools the (B, T, S, hidden_dim) latent representation and maps it to a
73
- compact embedding that is L2-normalized for InfoNCE / triplet losses.
 
74
  """
75
 
76
- def __init__(self, hidden_dim: int = 256, proj_dim: int = 128) -> None:
77
  super().__init__()
 
78
  self.pool = nn.AdaptiveAvgPool2d((1, hidden_dim))
79
  self.projection = nn.Sequential(
80
- nn.Linear(hidden_dim, proj_dim),
81
  nn.ReLU(),
82
- nn.Linear(proj_dim, proj_dim),
 
 
83
  )
84
 
85
  def forward(self, x: torch.Tensor) -> torch.Tensor:
86
  """
87
  x: (B, T, S, hidden_dim)
88
- Returns: (B, proj_dim) L2-normalized embeddings.
89
  """
90
  pooled = x.mean(dim=(1, 2)) # (B, hidden_dim)
91
- z = self.projection(pooled) # (B, proj_dim)
92
- return nn.functional.normalize(z, p=2, dim=1)
93
 
94
 
95
  class PIMTHeads(nn.Module):
96
- """Dual-headed multi-task output layer plus contrastive projection for the PIMT model."""
97
 
98
  def __init__(
99
  self,
100
  hidden_dim: int = 256,
101
  objective_dim: int = 138,
102
  num_classes_sub: int = 7,
103
- proj_dim: int = 128,
104
  ) -> None:
105
  super().__init__()
106
  self.objective = ObjectiveOdorHead(hidden_dim, objective_dim)
107
  self.subjective = SubjectiveSemanticHead(hidden_dim, num_classes_sub)
108
- self.contrastive = ContrastiveProjectionHead(hidden_dim, proj_dim)
109
 
110
  def forward(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
111
  """
112
  x: (B, T, S, hidden_dim)
113
- Returns dict with 'objective', 'subjective', and 'contrastive' outputs.
114
  """
115
  return {
116
  "objective": self.objective(x), # (B, T, 138)
117
  "subjective": self.subjective(x), # (B, 7)
118
- "contrastive": self.contrastive(x), # (B, proj_dim)
119
  }
 
65
  }
66
 
67
 
68
+ class ContinuousAlignmentHead(nn.Module):
69
  """
70
+ Dense perceptual alignment head.
71
 
72
+ Projects the latent mixture representation into the 138-D objective descriptor
73
+ space so that the predicted descriptor profile can be aligned with the true
74
+ 138-D target via cosine similarity, replacing the sparse InfoNCE loss.
75
  """
76
 
77
+ def __init__(self, hidden_dim: int = 256, output_dim: int = 138) -> None:
78
  super().__init__()
79
+ self.output_dim = output_dim
80
  self.pool = nn.AdaptiveAvgPool2d((1, hidden_dim))
81
  self.projection = nn.Sequential(
82
+ nn.Linear(hidden_dim, hidden_dim),
83
  nn.ReLU(),
84
+ nn.Dropout(0.1),
85
+ nn.Linear(hidden_dim, output_dim),
86
+ nn.Sigmoid(),
87
  )
88
 
89
  def forward(self, x: torch.Tensor) -> torch.Tensor:
90
  """
91
  x: (B, T, S, hidden_dim)
92
+ Returns: (B, output_dim) dense descriptor profile in [0, 1].
93
  """
94
  pooled = x.mean(dim=(1, 2)) # (B, hidden_dim)
95
+ return self.projection(pooled) # (B, output_dim)
 
96
 
97
 
98
  class PIMTHeads(nn.Module):
99
+ """Dual-headed multi-task output layer plus dense perceptual alignment head."""
100
 
101
  def __init__(
102
  self,
103
  hidden_dim: int = 256,
104
  objective_dim: int = 138,
105
  num_classes_sub: int = 7,
 
106
  ) -> None:
107
  super().__init__()
108
  self.objective = ObjectiveOdorHead(hidden_dim, objective_dim)
109
  self.subjective = SubjectiveSemanticHead(hidden_dim, num_classes_sub)
110
+ self.alignment = ContinuousAlignmentHead(hidden_dim, objective_dim)
111
 
112
  def forward(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
113
  """
114
  x: (B, T, S, hidden_dim)
115
+ Returns dict with 'objective', 'subjective', and 'alignment' outputs.
116
  """
117
  return {
118
  "objective": self.objective(x), # (B, T, 138)
119
  "subjective": self.subjective(x), # (B, 7)
120
+ "alignment": self.alignment(x), # (B, 138)
121
  }
src/pino/pimt_model_hf.py CHANGED
@@ -99,9 +99,11 @@ class PhysicsInformedMixtureTransformer(PreTrainedModel):
99
  )
100
  self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=config.num_layers)
101
  self.text_proj = nn.Linear(config.text_embedding_dim, config.hidden_dim)
 
 
102
  self.heads = PIMTHeads(
103
  hidden_dim=config.hidden_dim,
104
- objective_dim=config.embedding_dim,
105
  num_classes_sub=getattr(config, "num_classes_sub", 7),
106
  )
107
 
@@ -149,8 +151,8 @@ class PhysicsInformedMixtureTransformer(PreTrainedModel):
149
  return_dict = return_dict if return_dict is not None else self.config.return_dict
150
 
151
  if labels is not None:
152
- labels_obj = labels[..., : self.config.embedding_dim]
153
- labels_sub = labels[..., self.config.embedding_dim :]
154
 
155
  gated = self.gating(tokens, physics) # (B, T, S, E)
156
  b, t, s, e = gated.shape
@@ -170,16 +172,27 @@ class PhysicsInformedMixtureTransformer(PreTrainedModel):
170
  text_gate = F.sigmoid(text_hidden).view(b, 1, 1, self.hidden_dim) # (B, 1, 1, H)
171
  x = x * text_gate
172
 
173
- logits = self.heads(x) # {"objective": (B, T, 138), "subjective": (B, 7)}
174
 
 
 
175
  subjective_expanded = logits["subjective"].unsqueeze(1).expand(-1, t, -1)
176
- fused_logits = torch.cat([logits["objective"], subjective_expanded], dim=-1)
 
 
 
 
 
 
 
177
 
178
  loss = None
179
- if labels_obj is not None and labels_sub is not None:
 
 
180
  loss = self._compute_multitask_loss(
181
  logits["objective"], labels_obj, logits["subjective"], labels_sub
182
- )
183
 
184
  output = SequenceClassifierOutput(
185
  loss=loss,
 
99
  )
100
  self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=config.num_layers)
101
  self.text_proj = nn.Linear(config.text_embedding_dim, config.hidden_dim)
102
+ # Objective output vocabulary stays 138-D; structural input is 145-D.
103
+ objective_dim = getattr(config, "objective_dim", 138)
104
  self.heads = PIMTHeads(
105
  hidden_dim=config.hidden_dim,
106
+ objective_dim=objective_dim,
107
  num_classes_sub=getattr(config, "num_classes_sub", 7),
108
  )
109
 
 
151
  return_dict = return_dict if return_dict is not None else self.config.return_dict
152
 
153
  if labels is not None:
154
+ labels_obj = labels[..., :138]
155
+ labels_sub = labels[..., 138:]
156
 
157
  gated = self.gating(tokens, physics) # (B, T, S, E)
158
  b, t, s, e = gated.shape
 
172
  text_gate = F.sigmoid(text_hidden).view(b, 1, 1, self.hidden_dim) # (B, 1, 1, H)
173
  x = x * text_gate
174
 
175
+ logits = self.heads(x) # {"objective": (B, T, 138), "subjective": (B, 7), "alignment": (B, 138)}
176
 
177
+ # Fuse objective trajectory + subjective + alignment into a single tensor
178
+ # for HF Trainer labels (obj T x 138, then subjective 7, then alignment 138).
179
  subjective_expanded = logits["subjective"].unsqueeze(1).expand(-1, t, -1)
180
+ alignment_expanded = logits["alignment"].unsqueeze(1).expand(-1, t, -1)
181
+ fused_logits = torch.cat([logits["objective"], subjective_expanded, alignment_expanded], dim=-1)
182
+
183
+ # Labels are fused (B, T, 138 + 7 + 138) = (B, T, 283) in HF Trainer.
184
+ if labels is not None:
185
+ labels_obj = labels[..., :138]
186
+ labels_sub = labels[..., 138:145]
187
+ labels_alignment = labels[..., 145:283]
188
 
189
  loss = None
190
+ if labels_obj is not None and labels_sub is not None and labels_alignment is not None:
191
+ alignment_target = labels_alignment.mean(dim=1) # (B, 138)
192
+ alignment_loss = 1.0 - F.cosine_similarity(logits["alignment"], alignment_target, dim=-1).mean()
193
  loss = self._compute_multitask_loss(
194
  logits["objective"], labels_obj, logits["subjective"], labels_sub
195
+ ) + alignment_loss
196
 
197
  output = SequenceClassifierOutput(
198
  loss=loss,
src/pino/thermo/losses.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+
5
+ class DeepSeekLossBalancer(nn.Module):
6
+ """
7
+ Adaptive multi-task loss balancer inspired by DeepSeek's dynamic loss scaling.
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
+ losses = torch.stack(list(loss_dict.values()))
29
+
30
+ if not self._initialized.item() or torch.all(self.initial_losses == 0):
31
+ self.initial_losses.copy_(losses.detach().clamp(min=1e-5))
32
+ self.running_losses.copy_(losses.detach().clamp(min=1e-5))
33
+ self._initialized.fill_(True)
34
+
35
+ self.running_losses.copy_(
36
+ self.momentum * self.running_losses + (1 - self.momentum) * losses.detach()
37
+ )
38
+
39
+ ratios = self.running_losses / self.initial_losses
40
+ weights = ratios / (torch.sum(ratios) + 1e-8)
41
+ total_loss = torch.sum(losses * weights * float(len(losses)))
42
+
43
+ return total_loss
src/pino/train.py CHANGED
@@ -16,6 +16,7 @@ from torch.utils.tensorboard import SummaryWriter
16
 
17
  from pino.heads import PIMTHeads
18
  from pino.pimt_model import FragranceTrajectoryDataset, PhysicsInformedMixtureTransformer
 
19
  from pino.upload_data import create_formula_disjoint_split
20
 
21
  logger = logging.getLogger("pino.train")
@@ -83,18 +84,19 @@ def multitask_loss(
83
  target_obj: torch.Tensor,
84
  pred_sub: dict[str, torch.Tensor],
85
  target_sub: dict[str, torch.Tensor],
86
- z: torch.Tensor,
87
- labels_genre: torch.Tensor,
88
- weights: dict[str, float] | None = None,
89
- temperature: float = 0.1,
90
  ) -> tuple[torch.Tensor, dict[str, float]]:
91
  """
92
- Weighted multi-task loss: MSE for objective trajectory + cross-entropy for
93
- seasonality + MSE for gender + BCE for multi-label wearability + InfoNCE
94
- contrastive loss on the latent projection.
 
 
 
 
 
95
  """
96
- weights = weights or {"obj": 1.0, "season": 0.5, "gender": 0.25, "wear": 0.25, "contrastive": 0.5}
97
-
98
  # Objective MSE with padding mask over time.
99
  obj_mask = (target_obj.sum(dim=-1) > 0).float().unsqueeze(-1)
100
  obj_loss = nn.functional.mse_loss(pred_obj, target_obj, reduction="none")
@@ -103,71 +105,44 @@ def multitask_loss(
103
  season_loss = nn.functional.cross_entropy(pred_sub["seasonality"], target_sub["seasonality"].argmax(dim=-1))
104
  gender_loss = nn.functional.mse_loss(pred_sub["gender_profile"].squeeze(-1), target_sub["gender_profile"])
105
  wear_loss = nn.functional.binary_cross_entropy_with_logits(pred_sub["wearability"], target_sub["wearability"])
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
- # InfoNCE contrastive loss: maximize cosine similarity between samples with
108
- # the same human olfactory tag (genre) and minimize it for different tags.
109
- contrastive_loss = info_nce_loss(z, labels_genre, temperature=temperature)
110
-
111
- total = (
112
- weights["obj"] * obj_loss
113
- + weights["season"] * season_loss
114
- + weights["gender"] * gender_loss
115
- + weights["wear"] * wear_loss
116
- + weights["contrastive"] * contrastive_loss
117
- )
118
  components = {
119
  "obj": obj_loss.item(),
120
  "season": season_loss.item(),
121
- "gender": gender_loss.item(),
122
  "wear": wear_loss.item(),
123
- "contrastive": contrastive_loss.item(),
124
  "total": total.item(),
125
  }
126
  return total, components
127
 
128
 
129
- def info_nce_loss(z: torch.Tensor, labels: torch.Tensor, temperature: float = 0.1) -> torch.Tensor:
130
- """
131
- InfoNCE loss over L2-normalized embeddings using genre labels as positives.
132
-
133
- Args:
134
- z: (B, D) L2-normalized embeddings.
135
- labels: (B,) integer genre labels.
136
- temperature: softmax temperature.
137
- Returns:
138
- Scalar InfoNCE loss.
139
- """
140
- similarity = torch.matmul(z, z.T) / temperature # (B, B)
141
- labels = labels.view(-1, 1)
142
- mask_positive = (labels == labels.T).float() # (B, B)
143
- # Remove self-similarity from positives.
144
- logits_mask = torch.ones_like(mask_positive)
145
- logits_mask.fill_diagonal_(0)
146
- mask_positive = mask_positive * logits_mask
147
-
148
- # For each anchor, denominator is over all negatives + positives except self.
149
- exp_logits = torch.exp(similarity) * logits_mask
150
- log_prob = similarity - torch.log(exp_logits.sum(1, keepdim=True) + 1e-12)
151
-
152
- # Mean log-prob over positive pairs.
153
- mean_log_prob_pos = (mask_positive * log_prob).sum(1) / mask_positive.sum(1).clamp_min(1.0)
154
- loss = -mean_log_prob_pos.mean()
155
- return loss
156
-
157
-
158
  def train_epoch(
159
  model: nn.Module,
160
  heads: nn.Module,
161
  loader: DataLoader,
162
  optimizer: optim.Optimizer,
163
  device: torch.device,
164
- weights: dict[str, float],
165
  max_batches: int | None = None,
166
  ) -> dict[str, float]:
167
  model.train()
168
  heads.train()
169
  total_loss = 0.0
170
- totals = {"obj": 0.0, "season": 0.0, "gender": 0.0, "wear": 0.0, "contrastive": 0.0}
171
  count = 0
172
 
173
  for batch_idx, batch in enumerate(loader, start=1):
@@ -182,13 +157,12 @@ def train_epoch(
182
  "gender_profile": batch["target_sub_gender"].to(device),
183
  "wearability": batch["target_sub_wearability"].to(device),
184
  }
185
- labels_genre = batch["genre_label"].to(device)
186
  optimizer.zero_grad()
187
  latent = model(tokens, physics, src_key_padding_mask) # (B, T, S, H)
188
  pred = heads(latent)
189
  loss, comps = multitask_loss(
190
  pred["objective"], target_obj, pred["subjective"], target_sub,
191
- pred["contrastive"], labels_genre, weights,
192
  )
193
  loss.backward()
194
  torch.nn.utils.clip_grad_norm_(list(model.parameters()) + list(heads.parameters()), 1.0)
@@ -199,8 +173,8 @@ def train_epoch(
199
  totals[k] += comps[k]
200
  count += 1
201
  logger.info(
202
- "Batch %d | total=%.4f | obj=%.4f | season=%.4f | gender=%.4f | wear=%.4f | contrastive=%.4f",
203
- batch_idx, comps["total"], comps["obj"], comps["season"], comps["gender"], comps["wear"], comps["contrastive"],
204
  )
205
 
206
  return {k: v / max(count, 1) for k, v in {**totals, "total": total_loss}.items()}
@@ -212,12 +186,12 @@ def validate(
212
  heads: nn.Module,
213
  loader: DataLoader,
214
  device: torch.device,
215
- weights: dict[str, float],
216
  ) -> dict[str, float]:
217
  model.eval()
218
  heads.eval()
219
  total_loss = 0.0
220
- totals = {"obj": 0.0, "season": 0.0, "gender": 0.0, "wear": 0.0, "contrastive": 0.0}
221
  count = 0
222
 
223
  for batch in loader:
@@ -230,12 +204,11 @@ def validate(
230
  "gender_profile": batch["target_sub_gender"].to(device),
231
  "wearability": batch["target_sub_wearability"].to(device),
232
  }
233
- labels_genre = batch["genre_label"].to(device)
234
  latent = model(tokens, physics, src_key_padding_mask)
235
  pred = heads(latent)
236
  loss, comps = multitask_loss(
237
  pred["objective"], target_obj, pred["subjective"], target_sub,
238
- pred["contrastive"], labels_genre, weights,
239
  )
240
  total_loss += comps["total"]
241
  for k in totals:
@@ -346,7 +319,7 @@ def main():
346
  optimizer = optim.AdamW(params, lr=cfg["lr"], weight_decay=cfg["weight_decay"])
347
  scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs)
348
 
349
- weights = {"obj": 1.0, "season": 0.5, "gender": 0.25, "wear": 0.25, "contrastive": 0.5}
350
 
351
  writer = SummaryWriter(log_dir=args.log_dir)
352
  output_dir = Path(args.output_dir)
@@ -355,8 +328,8 @@ def main():
355
 
356
  best_val = float("inf")
357
  for epoch in range(1, args.epochs + 1):
358
- train_metrics = train_epoch(model, heads, train_loader, optimizer, device, weights, max_batches=cfg["max_batches_per_epoch"])
359
- val_metrics = validate(model, heads, val_loader, device, weights)
360
  scheduler.step()
361
 
362
  for split, metrics in [("train", train_metrics), ("val", val_metrics)]:
@@ -364,9 +337,9 @@ def main():
364
  writer.add_scalar(f"{split}/{k}", v, epoch)
365
 
366
  logger.info(
367
- "Epoch %d/%d | train_total=%.4f | val_total=%.4f | obj=%.4f | season=%.4f | gender=%.4f | wear=%.4f | contrastive=%.4f",
368
  epoch, args.epochs, train_metrics["total"], val_metrics["total"],
369
- val_metrics["obj"], val_metrics["season"], val_metrics["gender"], val_metrics["wear"], val_metrics["contrastive"],
370
  )
371
 
372
  if val_metrics["total"] < best_val:
@@ -380,10 +353,10 @@ def main():
380
  }, checkpoint_path)
381
  logger.info("Saved best checkpoint to %s", checkpoint_path)
382
 
383
- val_final_metrics = validate(model, heads, val_loader, device, weights)
384
  logger.info(
385
- "Final Val | total=%.4f | obj=%.4f | season=%.4f | gender=%.4f | wear=%.4f | contrastive=%.4f",
386
- val_final_metrics["total"], val_final_metrics["obj"], val_final_metrics["season"], val_final_metrics["gender"], val_final_metrics["wear"], val_final_metrics["contrastive"],
387
  )
388
  writer.close()
389
  return checkpoint_path
 
16
 
17
  from pino.heads import PIMTHeads
18
  from pino.pimt_model import FragranceTrajectoryDataset, PhysicsInformedMixtureTransformer
19
+ from pino.thermo.losses import DeepSeekLossBalancer
20
  from pino.upload_data import create_formula_disjoint_split
21
 
22
  logger = logging.getLogger("pino.train")
 
84
  target_obj: torch.Tensor,
85
  pred_sub: dict[str, torch.Tensor],
86
  target_sub: dict[str, torch.Tensor],
87
+ pred_alignment: torch.Tensor,
88
+ loss_balancer: DeepSeekLossBalancer,
 
 
89
  ) -> tuple[torch.Tensor, dict[str, float]]:
90
  """
91
+ Adaptive multi-task loss using the DeepSeekLossBalancer.
92
+
93
+ Tasks:
94
+ - obj: MSE over the 138-D time-resolved objective trajectory.
95
+ - season: cross-entropy over seasonality logits.
96
+ - wear: combined gender MSE + multi-label wearability BCE.
97
+ - alignment: 1 - cosine similarity between predicted and true 138-D descriptor
98
+ profiles (continuous, dense perceptual alignment).
99
  """
 
 
100
  # Objective MSE with padding mask over time.
101
  obj_mask = (target_obj.sum(dim=-1) > 0).float().unsqueeze(-1)
102
  obj_loss = nn.functional.mse_loss(pred_obj, target_obj, reduction="none")
 
105
  season_loss = nn.functional.cross_entropy(pred_sub["seasonality"], target_sub["seasonality"].argmax(dim=-1))
106
  gender_loss = nn.functional.mse_loss(pred_sub["gender_profile"].squeeze(-1), target_sub["gender_profile"])
107
  wear_loss = nn.functional.binary_cross_entropy_with_logits(pred_sub["wearability"], target_sub["wearability"])
108
+ wear_loss = wear_loss + gender_loss
109
+
110
+ # Continuous cosine alignment between predicted 138-D descriptor profile and
111
+ # the mean-pooled true objective trajectory over time.
112
+ true_profile = target_obj.mean(dim=1) # (B, 138)
113
+ alignment_loss = 1.0 - nn.functional.cosine_similarity(pred_alignment, true_profile, dim=-1).mean()
114
+
115
+ loss_payload = {
116
+ "obj": obj_loss,
117
+ "season": season_loss,
118
+ "wear": wear_loss,
119
+ "alignment": alignment_loss,
120
+ }
121
 
122
+ total = loss_balancer(loss_payload)
 
 
 
 
 
 
 
 
 
 
123
  components = {
124
  "obj": obj_loss.item(),
125
  "season": season_loss.item(),
 
126
  "wear": wear_loss.item(),
127
+ "alignment": alignment_loss.item(),
128
  "total": total.item(),
129
  }
130
  return total, components
131
 
132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  def train_epoch(
134
  model: nn.Module,
135
  heads: nn.Module,
136
  loader: DataLoader,
137
  optimizer: optim.Optimizer,
138
  device: torch.device,
139
+ loss_balancer: DeepSeekLossBalancer,
140
  max_batches: int | None = None,
141
  ) -> dict[str, float]:
142
  model.train()
143
  heads.train()
144
  total_loss = 0.0
145
+ totals = {"obj": 0.0, "season": 0.0, "wear": 0.0, "alignment": 0.0}
146
  count = 0
147
 
148
  for batch_idx, batch in enumerate(loader, start=1):
 
157
  "gender_profile": batch["target_sub_gender"].to(device),
158
  "wearability": batch["target_sub_wearability"].to(device),
159
  }
 
160
  optimizer.zero_grad()
161
  latent = model(tokens, physics, src_key_padding_mask) # (B, T, S, H)
162
  pred = heads(latent)
163
  loss, comps = multitask_loss(
164
  pred["objective"], target_obj, pred["subjective"], target_sub,
165
+ pred["alignment"], loss_balancer,
166
  )
167
  loss.backward()
168
  torch.nn.utils.clip_grad_norm_(list(model.parameters()) + list(heads.parameters()), 1.0)
 
173
  totals[k] += comps[k]
174
  count += 1
175
  logger.info(
176
+ "Batch %d | total=%.4f | obj=%.4f | season=%.4f | wear=%.4f | alignment=%.4f",
177
+ batch_idx, comps["total"], comps["obj"], comps["season"], comps["wear"], comps["alignment"],
178
  )
179
 
180
  return {k: v / max(count, 1) for k, v in {**totals, "total": total_loss}.items()}
 
186
  heads: nn.Module,
187
  loader: DataLoader,
188
  device: torch.device,
189
+ loss_balancer: DeepSeekLossBalancer,
190
  ) -> dict[str, float]:
191
  model.eval()
192
  heads.eval()
193
  total_loss = 0.0
194
+ totals = {"obj": 0.0, "season": 0.0, "wear": 0.0, "alignment": 0.0}
195
  count = 0
196
 
197
  for batch in loader:
 
204
  "gender_profile": batch["target_sub_gender"].to(device),
205
  "wearability": batch["target_sub_wearability"].to(device),
206
  }
 
207
  latent = model(tokens, physics, src_key_padding_mask)
208
  pred = heads(latent)
209
  loss, comps = multitask_loss(
210
  pred["objective"], target_obj, pred["subjective"], target_sub,
211
+ pred["alignment"], loss_balancer,
212
  )
213
  total_loss += comps["total"]
214
  for k in totals:
 
319
  optimizer = optim.AdamW(params, lr=cfg["lr"], weight_decay=cfg["weight_decay"])
320
  scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs)
321
 
322
+ loss_balancer = DeepSeekLossBalancer(num_tasks=4).to(device)
323
 
324
  writer = SummaryWriter(log_dir=args.log_dir)
325
  output_dir = Path(args.output_dir)
 
328
 
329
  best_val = float("inf")
330
  for epoch in range(1, args.epochs + 1):
331
+ train_metrics = train_epoch(model, heads, train_loader, optimizer, device, loss_balancer, max_batches=cfg.get("max_batches_per_epoch"))
332
+ val_metrics = validate(model, heads, val_loader, device, loss_balancer)
333
  scheduler.step()
334
 
335
  for split, metrics in [("train", train_metrics), ("val", val_metrics)]:
 
337
  writer.add_scalar(f"{split}/{k}", v, epoch)
338
 
339
  logger.info(
340
+ "Epoch %d/%d | train_total=%.4f | val_total=%.4f | obj=%.4f | season=%.4f | wear=%.4f | alignment=%.4f",
341
  epoch, args.epochs, train_metrics["total"], val_metrics["total"],
342
+ val_metrics["obj"], val_metrics["season"], val_metrics["wear"], val_metrics["alignment"],
343
  )
344
 
345
  if val_metrics["total"] < best_val:
 
353
  }, checkpoint_path)
354
  logger.info("Saved best checkpoint to %s", checkpoint_path)
355
 
356
+ val_final_metrics = validate(model, heads, val_loader, device, loss_balancer)
357
  logger.info(
358
+ "Final Val | total=%.4f | obj=%.4f | season=%.4f | wear=%.4f | alignment=%.4f",
359
+ val_final_metrics["total"], val_final_metrics["obj"], val_final_metrics["season"], val_final_metrics["wear"], val_final_metrics["alignment"],
360
  )
361
  writer.close()
362
  return checkpoint_path
src/pino/train_hf.py CHANGED
@@ -45,12 +45,12 @@ def pad_trajectory_collate(batch: list) -> dict:
45
  max_molecules = max(item["tokens"].size(0) for item in batch)
46
  max_timesteps = max(item["physics"].size(0) for item in batch)
47
  bsz = len(batch)
48
-
49
  tokens = torch.zeros(bsz, max_molecules, 145, dtype=torch.float32)
50
  physics = torch.zeros(bsz, max_timesteps, max_molecules, 2, dtype=torch.float32)
51
  src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
52
  labels_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
53
  labels_sub = torch.zeros(bsz, 7, dtype=torch.float32)
 
54
 
55
  # Encode text on-the-fly using sentence-transformers only if a record is missing
56
  # its pre-computed embedding. This avoids loading the encoder inside forked
@@ -179,11 +179,11 @@ def main() -> None:
179
 
180
  config = PIMTConfig(
181
  embedding_dim=145,
 
182
  state_dim=2,
183
  hidden_dim=256,
184
  num_heads=8,
185
  num_layers=4,
186
- dropout=0.1,
187
  num_classes_sub=7,
188
  )
189
  model = PhysicsInformedMixtureTransformer(config)
 
45
  max_molecules = max(item["tokens"].size(0) for item in batch)
46
  max_timesteps = max(item["physics"].size(0) for item in batch)
47
  bsz = len(batch)
 
48
  tokens = torch.zeros(bsz, max_molecules, 145, dtype=torch.float32)
49
  physics = torch.zeros(bsz, max_timesteps, max_molecules, 2, dtype=torch.float32)
50
  src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
51
  labels_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
52
  labels_sub = torch.zeros(bsz, 7, dtype=torch.float32)
53
+ genre_labels = torch.zeros(bsz, dtype=torch.int64)
54
 
55
  # Encode text on-the-fly using sentence-transformers only if a record is missing
56
  # its pre-computed embedding. This avoids loading the encoder inside forked
 
179
 
180
  config = PIMTConfig(
181
  embedding_dim=145,
182
+ objective_dim=138,
183
  state_dim=2,
184
  hidden_dim=256,
185
  num_heads=8,
186
  num_layers=4,
 
187
  num_classes_sub=7,
188
  )
189
  model = PhysicsInformedMixtureTransformer(config)