mattbitzesty commited on
Commit
8ce6ce2
·
unverified ·
1 Parent(s): 14a2d75

feat(pino): publication-grade training telemetry and fused multi-task labels

Browse files

- Add seed_everything for reproducibility

- Add compute_metrics for objective MSE and subjective MAE

- Fuse labels into single (B,T,145) tensor for HF Trainer

- Export publication_metrics.json after training

- Add load_best_model_at_end and tensorboard logging

Files changed (2) hide show
  1. src/pino/pimt_model_hf.py +29 -12
  2. src/pino/train_hf.py +87 -10
src/pino/pimt_model_hf.py CHANGED
@@ -13,6 +13,8 @@ from .heads import PIMTHeads
13
  class PIMTConfig(PretrainedConfig):
14
  """
15
  Hugging Face PretrainedConfig for the Physics-Informed Mixture Transformer.
 
 
16
  """
17
 
18
  model_type = "pimt"
@@ -37,6 +39,7 @@ class PIMTConfig(PretrainedConfig):
37
  self.dropout = dropout
38
  self.max_ingredients = max_ingredients
39
  self.num_classes_sub = num_classes_sub
 
40
  super().__init__(**kwargs)
41
 
42
 
@@ -122,6 +125,9 @@ class PhysicsInformedMixtureTransformer(PreTrainedModel):
122
  obj_loss = nn.functional.mse_loss(pred_obj, target_obj, reduction="none")
123
  obj_loss = (obj_loss * obj_mask).sum() / obj_mask.sum().clamp_min(1.0)
124
 
 
 
 
125
  sub_loss = nn.functional.mse_loss(pred_sub, target_sub)
126
 
127
  total = weights["obj"] * obj_loss + weights["sub"] * sub_loss
@@ -132,6 +138,7 @@ class PhysicsInformedMixtureTransformer(PreTrainedModel):
132
  tokens: torch.Tensor,
133
  physics: torch.Tensor,
134
  src_key_padding_mask: Optional[torch.Tensor] = None,
 
135
  labels_obj: Optional[torch.Tensor] = None,
136
  labels_sub: Optional[torch.Tensor] = None,
137
  return_dict: Optional[bool] = None,
@@ -140,11 +147,17 @@ class PhysicsInformedMixtureTransformer(PreTrainedModel):
140
  tokens: (B, S, E)
141
  physics: (B, T, S, state_dim)
142
  src_key_padding_mask: (B, S) bool, True for padding positions.
143
- labels_obj: (B, T, E) optional objective targets.
144
- labels_sub: dict of optional subjective targets.
 
 
145
  """
146
  return_dict = return_dict if return_dict is not None else self.config.return_dict
147
 
 
 
 
 
148
  gated = self.gating(tokens, physics) # (B, T, S, E)
149
  b, t, s, e = gated.shape
150
  x = self.input_proj(gated) # (B, T, S, H)
@@ -160,21 +173,25 @@ class PhysicsInformedMixtureTransformer(PreTrainedModel):
160
 
161
  logits = self.heads(x) # {"objective": (B, T, 138), "subjective": (B, 7)}
162
 
163
- # Attach subjective logits to the output object for easy downstream access.
164
- output = SequenceClassifierOutput(
165
- loss=None,
166
- logits=logits["objective"],
167
- hidden_states=None,
168
- attentions=None,
169
- )
170
- output.subjective = logits["subjective"]
171
 
 
172
  if labels_obj is not None and labels_sub is not None:
173
- output.loss = self._compute_multitask_loss(
174
  logits["objective"], labels_obj, logits["subjective"], labels_sub
175
  )
176
 
 
 
 
 
 
 
 
177
  if not return_dict:
178
- return (output.loss, output.logits, output.subjective) if output.loss is not None else (output.logits, output.subjective)
179
 
180
  return output
 
13
  class PIMTConfig(PretrainedConfig):
14
  """
15
  Hugging Face PretrainedConfig for the Physics-Informed Mixture Transformer.
16
+ Defaults to returning tuples so the Trainer can capture both objective and
17
+ subjective head outputs for multi-task metric reporting.
18
  """
19
 
20
  model_type = "pimt"
 
39
  self.dropout = dropout
40
  self.max_ingredients = max_ingredients
41
  self.num_classes_sub = num_classes_sub
42
+ kwargs.setdefault("return_dict", True)
43
  super().__init__(**kwargs)
44
 
45
 
 
125
  obj_loss = nn.functional.mse_loss(pred_obj, target_obj, reduction="none")
126
  obj_loss = (obj_loss * obj_mask).sum() / obj_mask.sum().clamp_min(1.0)
127
 
128
+ # pred_sub is (B, 7), target_sub is (B, 7) or (B, T, 7); use mean over time if needed.
129
+ if target_sub.dim() == 3:
130
+ target_sub = target_sub.mean(dim=1)
131
  sub_loss = nn.functional.mse_loss(pred_sub, target_sub)
132
 
133
  total = weights["obj"] * obj_loss + weights["sub"] * sub_loss
 
138
  tokens: torch.Tensor,
139
  physics: torch.Tensor,
140
  src_key_padding_mask: Optional[torch.Tensor] = None,
141
+ labels: Optional[torch.Tensor] = None,
142
  labels_obj: Optional[torch.Tensor] = None,
143
  labels_sub: Optional[torch.Tensor] = None,
144
  return_dict: Optional[bool] = None,
 
147
  tokens: (B, S, E)
148
  physics: (B, T, S, state_dim)
149
  src_key_padding_mask: (B, S) bool, True for padding positions.
150
+ labels: fused (B, T, 145) tensor of objective + subjective labels. When
151
+ provided, it is split into labels_obj (first 138 dims) and
152
+ labels_sub (last 7 dims) for multi-task loss.
153
+ labels_obj / labels_sub: explicit optional labels, used if labels is None.
154
  """
155
  return_dict = return_dict if return_dict is not None else self.config.return_dict
156
 
157
+ if labels is not None:
158
+ labels_obj = labels[..., : self.config.embedding_dim]
159
+ labels_sub = labels[..., self.config.embedding_dim :]
160
+
161
  gated = self.gating(tokens, physics) # (B, T, S, E)
162
  b, t, s, e = gated.shape
163
  x = self.input_proj(gated) # (B, T, S, H)
 
173
 
174
  logits = self.heads(x) # {"objective": (B, T, 138), "subjective": (B, 7)}
175
 
176
+ # Fuse objective and subjective predictions into a single (B, T, 145) tensor
177
+ # so the HF Trainer can store both for multi-task compute_metrics.
178
+ subjective_expanded = logits["subjective"].unsqueeze(1).expand(-1, t, -1) # (B, T, 7)
179
+ fused_logits = torch.cat([logits["objective"], subjective_expanded], dim=-1) # (B, T, 145)
 
 
 
 
180
 
181
+ loss = None
182
  if labels_obj is not None and labels_sub is not None:
183
+ loss = self._compute_multitask_loss(
184
  logits["objective"], labels_obj, logits["subjective"], labels_sub
185
  )
186
 
187
+ output = SequenceClassifierOutput(
188
+ loss=loss,
189
+ logits=fused_logits,
190
+ hidden_states=None,
191
+ attentions=None,
192
+ )
193
+
194
  if not return_dict:
195
+ return (output.loss, output.logits) if output.loss is not None else (output.logits,)
196
 
197
  return output
src/pino/train_hf.py CHANGED
@@ -1,13 +1,16 @@
1
  from __future__ import annotations
2
 
 
3
  import logging
 
4
  import random
5
  from pathlib import Path
 
6
 
7
  import numpy as np
8
  import torch
 
9
  from datasets import load_dataset
10
- from huggingface_hub import hf_hub_download
11
  from transformers import Trainer, TrainingArguments
12
 
13
  from pino.pimt_model import FragranceTrajectoryDataset
@@ -16,9 +19,18 @@ from pino.pimt_model_hf import PIMTConfig, PhysicsInformedMixtureTransformer
16
  logger = logging.getLogger("pino.train_hf")
17
 
18
 
 
 
 
 
 
 
 
 
 
 
19
  def pad_trajectory_collate(batch: list) -> dict:
20
  """Custom collate for variable-length ingredient formulations."""
21
- import torch
22
  max_molecules = max(item["tokens"].size(0) for item in batch)
23
  max_timesteps = max(item["physics"].size(0) for item in batch)
24
  bsz = len(batch)
@@ -38,15 +50,77 @@ def pad_trajectory_collate(batch: list) -> dict:
38
  labels_obj[i, :t_steps] = item["target_obj"]
39
  labels_sub[i] = item["target_sub"]
40
 
 
 
 
 
41
  return {
42
  "tokens": tokens,
43
  "physics": physics,
44
  "src_key_padding_mask": src_key_padding_mask,
45
- "labels_obj": labels_obj,
46
- "labels_sub": labels_sub,
47
  }
48
 
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  def run_training() -> None:
51
  """Entry point used by the Hugging Face training Space."""
52
  main()
@@ -59,10 +133,8 @@ def main() -> None:
59
  )
60
  logger.info("Training PIMT with Hugging Face transformers")
61
 
62
- seed = 2026
63
- torch.manual_seed(seed)
64
- np.random.seed(seed)
65
- random.seed(seed)
66
 
67
  # Load the verified stratified partitions from the Hugging Face Hub.
68
  logger.info("Loading PINO synthetic dataset from Hugging Face Hub")
@@ -85,7 +157,7 @@ def main() -> None:
85
  model = PhysicsInformedMixtureTransformer(config)
86
 
87
  training_args = TrainingArguments(
88
- output_dir="./models/pino_cloud_weights",
89
  overwrite_output_dir=True,
90
  do_train=True,
91
  do_eval=True,
@@ -98,11 +170,14 @@ def main() -> None:
98
  dataloader_num_workers=2,
99
  dataloader_pin_memory=True,
100
  logging_steps=10,
101
- logging_dir="./logs",
102
  logging_strategy="steps",
103
  report_to=["tensorboard"],
104
  save_strategy="epoch",
105
  save_total_limit=2,
 
 
 
106
  disable_tqdm=False,
107
  seed=seed,
108
  remove_unused_columns=False,
@@ -117,9 +192,11 @@ def main() -> None:
117
  train_dataset=train_ds,
118
  eval_dataset=val_ds,
119
  data_collator=pad_trajectory_collate,
 
120
  )
121
 
122
  trainer.train()
 
123
  logger.info("HF training complete")
124
 
125
 
 
1
  from __future__ import annotations
2
 
3
+ import json
4
  import logging
5
+ import os
6
  import random
7
  from pathlib import Path
8
+ from typing import Any
9
 
10
  import numpy as np
11
  import torch
12
+ import torch.nn.functional as F
13
  from datasets import load_dataset
 
14
  from transformers import Trainer, TrainingArguments
15
 
16
  from pino.pimt_model import FragranceTrajectoryDataset
 
19
  logger = logging.getLogger("pino.train_hf")
20
 
21
 
22
+ def seed_everything(seed: int = 42) -> None:
23
+ """Lock all RNGs for fully reproducible training runs."""
24
+ random.seed(seed)
25
+ os.environ["PYTHONHASHSEED"] = str(seed)
26
+ np.random.seed(seed)
27
+ torch.manual_seed(seed)
28
+ torch.cuda.manual_seed(seed)
29
+ torch.backends.cudnn.deterministic = True
30
+
31
+
32
  def pad_trajectory_collate(batch: list) -> dict:
33
  """Custom collate for variable-length ingredient formulations."""
 
34
  max_molecules = max(item["tokens"].size(0) for item in batch)
35
  max_timesteps = max(item["physics"].size(0) for item in batch)
36
  bsz = len(batch)
 
50
  labels_obj[i, :t_steps] = item["target_obj"]
51
  labels_sub[i] = item["target_sub"]
52
 
53
+ # Fuse objective and subjective labels into a single (B, T, 145) tensor for HF Trainer.
54
+ labels_sub_t = labels_sub.unsqueeze(1).expand(-1, max_timesteps, -1)
55
+ labels = torch.cat([labels_obj, labels_sub_t], dim=-1)
56
+
57
  return {
58
  "tokens": tokens,
59
  "physics": physics,
60
  "src_key_padding_mask": src_key_padding_mask,
61
+ "labels": labels,
 
62
  }
63
 
64
 
65
+ def compute_metrics(eval_pred) -> dict[str, float]:
66
+ """
67
+ Compute isolated objective and subjective metrics from eval predictions.
68
+ """
69
+ predictions, labels = eval_pred
70
+
71
+ obj_pred = predictions[:, :, :138]
72
+ obj_true = labels[:, :, :138]
73
+
74
+ sub_pred = predictions[:, 0, 138:]
75
+ sub_true = labels[:, 0, 138:]
76
+
77
+ obj_mse = float(np.mean((obj_pred - obj_true) ** 2))
78
+ sub_mae = float(np.mean(np.abs(sub_pred - sub_true)))
79
+
80
+ return {
81
+ "objective_mse": round(obj_mse, 6),
82
+ "subjective_mae": round(sub_mae, 6),
83
+ "eval_loss": round(obj_mse + 0.5 * sub_mae, 6),
84
+ }
85
+
86
+
87
+ def export_publication_metrics(
88
+ trainer: Trainer,
89
+ val_ds: FragranceTrajectoryDataset,
90
+ output_path: str = "data/publication_metrics.json",
91
+ ) -> None:
92
+ """Run evaluation on the validation set and save raw prediction/target pairs."""
93
+ logger.info("Exporting publication validation metrics to %s", output_path)
94
+ predictions = trainer.predict(val_ds)
95
+
96
+ pred_arr = predictions.predictions
97
+ true_arr = predictions.label_ids
98
+
99
+ obj_pred = pred_arr[:, :, :138]
100
+ obj_true = true_arr[:, :, :138]
101
+ sub_pred = pred_arr[:, 0, 138:]
102
+ sub_true = true_arr[:, 0, 138:]
103
+
104
+ # Save a subset (first 200 records) for graphing predicted-vs-actual.
105
+ subset_size = min(200, obj_pred.shape[0])
106
+ metrics = {
107
+ "objective": {
108
+ "predictions": obj_pred[:subset_size].tolist(),
109
+ "targets": obj_true[:subset_size].tolist(),
110
+ "mse": float(np.mean((obj_pred - obj_true) ** 2)),
111
+ },
112
+ "subjective": {
113
+ "predictions": sub_pred[:subset_size].tolist(),
114
+ "targets": sub_true[:subset_size].tolist(),
115
+ "mae": float(np.mean(np.abs(sub_pred - sub_true))),
116
+ },
117
+ }
118
+
119
+ Path(output_path).parent.mkdir(parents=True, exist_ok=True)
120
+ Path(output_path).write_text(json.dumps(metrics, indent=2))
121
+ logger.info("Publication metrics saved")
122
+
123
+
124
  def run_training() -> None:
125
  """Entry point used by the Hugging Face training Space."""
126
  main()
 
133
  )
134
  logger.info("Training PIMT with Hugging Face transformers")
135
 
136
+ seed = 42
137
+ seed_everything(seed)
 
 
138
 
139
  # Load the verified stratified partitions from the Hugging Face Hub.
140
  logger.info("Loading PINO synthetic dataset from Hugging Face Hub")
 
157
  model = PhysicsInformedMixtureTransformer(config)
158
 
159
  training_args = TrainingArguments(
160
+ output_dir="./models/pino_publication_run",
161
  overwrite_output_dir=True,
162
  do_train=True,
163
  do_eval=True,
 
170
  dataloader_num_workers=2,
171
  dataloader_pin_memory=True,
172
  logging_steps=10,
173
+ logging_dir="./logs/tensorboard",
174
  logging_strategy="steps",
175
  report_to=["tensorboard"],
176
  save_strategy="epoch",
177
  save_total_limit=2,
178
+ load_best_model_at_end=True,
179
+ metric_for_best_model="eval_loss",
180
+ greater_is_better=False,
181
  disable_tqdm=False,
182
  seed=seed,
183
  remove_unused_columns=False,
 
192
  train_dataset=train_ds,
193
  eval_dataset=val_ds,
194
  data_collator=pad_trajectory_collate,
195
+ compute_metrics=compute_metrics,
196
  )
197
 
198
  trainer.train()
199
+ export_publication_metrics(trainer, val_ds)
200
  logger.info("HF training complete")
201
 
202