Matthew Ford commited on
Commit ·
4cb605e
1
Parent(s): 4506f81
fix: normalize objective targets for pyramid training
Browse filesFormer-commit-id: 162a1778d696a4aea2bf3bd1781418fe7751ebce
Former-commit-id: 8019cedcf905b8fa216cbc0a61d9e356f8a68e2e
- src/pino/pimt_model.py +62 -1
- src/pino/train.py +40 -24
- tests/test_train_collate.py +50 -0
src/pino/pimt_model.py
CHANGED
|
@@ -21,6 +21,46 @@ DEFAULT_DATASET = Path(__file__).parent.parent.parent / "data" / "synthetic_data
|
|
| 21 |
DEFAULT_EMBEDDING_DIM = 151
|
| 22 |
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
class FragranceTrajectoryDataset(Dataset):
|
| 25 |
"""
|
| 26 |
Streaming PyTorch dataset over the PINO synthetic trajectory corpus.
|
|
@@ -50,6 +90,7 @@ class FragranceTrajectoryDataset(Dataset):
|
|
| 50 |
self.embedding_engine = OlfactoryEmbeddingEngine(use_fallback=use_embedding_fallback)
|
| 51 |
self.label_noise = label_noise
|
| 52 |
self.genre_map = genre_map or {}
|
|
|
|
| 53 |
self._index_offsets: list[int] = []
|
| 54 |
if self.records is None:
|
| 55 |
if self.data_path is None:
|
|
@@ -118,6 +159,7 @@ class FragranceTrajectoryDataset(Dataset):
|
|
| 118 |
objective_targets = np.array(record["objective_targets"], dtype=np.float32)
|
| 119 |
else:
|
| 120 |
objective_targets = get_objective_targets(strategy, t_steps)
|
|
|
|
| 121 |
|
| 122 |
if "psychometric_targets" in record:
|
| 123 |
psychometric_targets = np.array(record["psychometric_targets"], dtype=np.float32)
|
|
@@ -127,12 +169,31 @@ class FragranceTrajectoryDataset(Dataset):
|
|
| 127 |
from .semantics import get_psychometric_targets
|
| 128 |
psychometric_targets = get_psychometric_targets(strategy)
|
| 129 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
genre = record.get("metadata", {}).get("generation_strategy", "wildcard")
|
| 131 |
return {
|
| 132 |
"tokens": torch.stack(tokens, dim=0), # (num_molecules, feature_dim)
|
| 133 |
"physics": torch.from_numpy(states), # (num_timesteps, num_molecules, physics_dim=2)
|
| 134 |
-
"target_obj": torch.from_numpy(objective_targets), # (
|
| 135 |
"target_sub": torch.from_numpy(psychometric_targets), # (7,)
|
|
|
|
|
|
|
| 136 |
"genre_label": self.genre_map.get(genre, 0),
|
| 137 |
"genre": genre,
|
| 138 |
}
|
|
|
|
| 21 |
DEFAULT_EMBEDDING_DIM = 151
|
| 22 |
|
| 23 |
|
| 24 |
+
def objective_targets_to_pyramid(targets: np.ndarray | torch.Tensor) -> np.ndarray | torch.Tensor:
|
| 25 |
+
"""
|
| 26 |
+
Normalize objective labels to the current static pyramid shape (3, 138).
|
| 27 |
+
|
| 28 |
+
Older records store a time-resolved dry-down trajectory (T, 138). The
|
| 29 |
+
pyramid head predicts top/middle/base tiers, so legacy trajectories are
|
| 30 |
+
folded into early/middle/late windows using the strongest descriptor
|
| 31 |
+
evidence in each window.
|
| 32 |
+
"""
|
| 33 |
+
if targets.ndim != 2:
|
| 34 |
+
raise ValueError(f"objective targets must be 2-D, got shape {tuple(targets.shape)}")
|
| 35 |
+
if targets.shape == (3, 138):
|
| 36 |
+
return targets
|
| 37 |
+
if targets.shape[1] != 138:
|
| 38 |
+
raise ValueError(f"objective targets must have 138 descriptors, got shape {tuple(targets.shape)}")
|
| 39 |
+
|
| 40 |
+
if isinstance(targets, torch.Tensor):
|
| 41 |
+
chunks = torch.tensor_split(targets, 3, dim=0)
|
| 42 |
+
return torch.stack([chunk.max(dim=0).values for chunk in chunks], dim=0)
|
| 43 |
+
|
| 44 |
+
chunks = np.array_split(targets, 3, axis=0)
|
| 45 |
+
return np.stack([chunk.max(axis=0) for chunk in chunks], axis=0)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _load_poucher_substantivity_targets() -> dict[str, float]:
|
| 49 |
+
"""Measured Poucher log10 substantivity coefficients keyed by CAS."""
|
| 50 |
+
path = Path(__file__).parent.parent.parent / "data" / "poucher_substantivity.jsonl"
|
| 51 |
+
if not path.exists():
|
| 52 |
+
return {}
|
| 53 |
+
targets: dict[str, float] = {}
|
| 54 |
+
with path.open("r", encoding="utf-8") as f:
|
| 55 |
+
for line in f:
|
| 56 |
+
if not line.strip():
|
| 57 |
+
continue
|
| 58 |
+
row = json.loads(line)
|
| 59 |
+
coeff = float(row["poucher_coefficient"])
|
| 60 |
+
targets[str(row["cas"])] = float(np.log10(coeff))
|
| 61 |
+
return targets
|
| 62 |
+
|
| 63 |
+
|
| 64 |
class FragranceTrajectoryDataset(Dataset):
|
| 65 |
"""
|
| 66 |
Streaming PyTorch dataset over the PINO synthetic trajectory corpus.
|
|
|
|
| 90 |
self.embedding_engine = OlfactoryEmbeddingEngine(use_fallback=use_embedding_fallback)
|
| 91 |
self.label_noise = label_noise
|
| 92 |
self.genre_map = genre_map or {}
|
| 93 |
+
self.poucher_substantivity = _load_poucher_substantivity_targets()
|
| 94 |
self._index_offsets: list[int] = []
|
| 95 |
if self.records is None:
|
| 96 |
if self.data_path is None:
|
|
|
|
| 159 |
objective_targets = np.array(record["objective_targets"], dtype=np.float32)
|
| 160 |
else:
|
| 161 |
objective_targets = get_objective_targets(strategy, t_steps)
|
| 162 |
+
objective_targets = objective_targets_to_pyramid(objective_targets).astype(np.float32, copy=False)
|
| 163 |
|
| 164 |
if "psychometric_targets" in record:
|
| 165 |
psychometric_targets = np.array(record["psychometric_targets"], dtype=np.float32)
|
|
|
|
| 169 |
from .semantics import get_psychometric_targets
|
| 170 |
psychometric_targets = get_psychometric_targets(strategy)
|
| 171 |
|
| 172 |
+
measured_substantivity: list[tuple[float, float]] = []
|
| 173 |
+
for comp in formula:
|
| 174 |
+
cas = str(comp.get("cas", "")).replace("NATURAL:", "")
|
| 175 |
+
if cas in self.poucher_substantivity:
|
| 176 |
+
measured_substantivity.append((
|
| 177 |
+
float(comp.get("weight_fraction", 1.0)),
|
| 178 |
+
self.poucher_substantivity[cas],
|
| 179 |
+
))
|
| 180 |
+
if measured_substantivity:
|
| 181 |
+
weights = np.array([w for w, _v in measured_substantivity], dtype=np.float32)
|
| 182 |
+
values = np.array([v for _w, v in measured_substantivity], dtype=np.float32)
|
| 183 |
+
substantivity_target = float(np.average(values, weights=weights))
|
| 184 |
+
substantivity_mask = 1.0
|
| 185 |
+
else:
|
| 186 |
+
substantivity_target = 0.0
|
| 187 |
+
substantivity_mask = 0.0
|
| 188 |
+
|
| 189 |
genre = record.get("metadata", {}).get("generation_strategy", "wildcard")
|
| 190 |
return {
|
| 191 |
"tokens": torch.stack(tokens, dim=0), # (num_molecules, feature_dim)
|
| 192 |
"physics": torch.from_numpy(states), # (num_timesteps, num_molecules, physics_dim=2)
|
| 193 |
+
"target_obj": torch.from_numpy(objective_targets), # (3, 138)
|
| 194 |
"target_sub": torch.from_numpy(psychometric_targets), # (7,)
|
| 195 |
+
"target_substantivity": torch.tensor(substantivity_target, dtype=torch.float32),
|
| 196 |
+
"target_substantivity_mask": torch.tensor(substantivity_mask, dtype=torch.float32),
|
| 197 |
"genre_label": self.genre_map.get(genre, 0),
|
| 198 |
"genre": genre,
|
| 199 |
}
|
src/pino/train.py
CHANGED
|
@@ -17,7 +17,12 @@ from torch.utils.data import DataLoader
|
|
| 17 |
from torch.utils.tensorboard import SummaryWriter
|
| 18 |
|
| 19 |
from pino.heads import PIMTHeads
|
| 20 |
-
from pino.pimt_model import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
from pino.thermo.losses import AdaptiveLossBalancer
|
| 22 |
from pino.upload_data import create_formula_disjoint_split_from_records
|
| 23 |
|
|
@@ -50,17 +55,12 @@ def pad_trajectory_collate(batch: list[dict[str, Any]]) -> dict[str, Any]:
|
|
| 50 |
tokens = torch.zeros(bsz, max_molecules, DEFAULT_EMBEDDING_DIM, dtype=torch.float32)
|
| 51 |
physics = torch.zeros(bsz, max_timesteps, max_molecules, 2, dtype=torch.float32)
|
| 52 |
src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
|
| 53 |
-
|
| 54 |
-
# (3, 138) pyramid targets or (T, 138) legacy trajectories.
|
| 55 |
-
first_targets = batch[0]["target_obj"]
|
| 56 |
-
if first_targets.dim() == 2 and first_targets.size(0) == 3:
|
| 57 |
-
target_shape = (bsz, 3, 138)
|
| 58 |
-
else:
|
| 59 |
-
target_shape = (bsz, max_timesteps, 138)
|
| 60 |
-
target_obj = torch.zeros(*target_shape, dtype=torch.float32)
|
| 61 |
target_sub_seasonality = torch.zeros(bsz, 4, dtype=torch.float32)
|
| 62 |
target_sub_gender = torch.zeros(bsz, dtype=torch.float32)
|
| 63 |
target_sub_wearability = torch.zeros(bsz, 2, dtype=torch.float32)
|
|
|
|
|
|
|
| 64 |
genre_labels = torch.zeros(bsz, dtype=torch.int64)
|
| 65 |
|
| 66 |
for i, item in enumerate(batch):
|
|
@@ -69,11 +69,13 @@ def pad_trajectory_collate(batch: list[dict[str, Any]]) -> dict[str, Any]:
|
|
| 69 |
tokens[i, :n_mol] = item["tokens"]
|
| 70 |
physics[i, :t_steps, :n_mol] = item["physics"]
|
| 71 |
src_key_padding_mask[i, :n_mol] = False
|
| 72 |
-
target_obj[i] = item["target_obj"]
|
| 73 |
sub = item["target_sub"]
|
| 74 |
target_sub_seasonality[i] = sub[[0,1,2,3]]
|
| 75 |
target_sub_gender[i] = sub[4]
|
| 76 |
target_sub_wearability[i] = sub[[5,6]]
|
|
|
|
|
|
|
| 77 |
genre_labels[i] = item.get("genre_label", 0)
|
| 78 |
|
| 79 |
# Force padding positions to a neutral log10_OAV sentinel so the Synergistic
|
|
@@ -88,6 +90,8 @@ def pad_trajectory_collate(batch: list[dict[str, Any]]) -> dict[str, Any]:
|
|
| 88 |
"target_sub_seasonality": target_sub_seasonality,
|
| 89 |
"target_sub_gender": target_sub_gender,
|
| 90 |
"target_sub_wearability": target_sub_wearability,
|
|
|
|
|
|
|
| 91 |
"genre_label": genre_labels,
|
| 92 |
}
|
| 93 |
|
|
@@ -114,6 +118,12 @@ def multitask_loss(
|
|
| 114 |
gender_loss = nn.functional.mse_loss(pred_sub["gender_profile"].squeeze(-1), target_sub["gender_profile"])
|
| 115 |
wear_loss = nn.functional.binary_cross_entropy_with_logits(pred_sub["wearability"], target_sub["wearability"])
|
| 116 |
wear_loss = wear_loss + gender_loss
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
# Continuous cosine alignment between predicted 138-D descriptor profile and
|
| 119 |
# the mean of the true pyramid tiers over the three tiers. This keeps the
|
|
@@ -125,6 +135,7 @@ def multitask_loss(
|
|
| 125 |
"obj": obj_loss,
|
| 126 |
"season": season_loss,
|
| 127 |
"wear": wear_loss,
|
|
|
|
| 128 |
"alignment": alignment_loss,
|
| 129 |
}
|
| 130 |
|
|
@@ -133,6 +144,7 @@ def multitask_loss(
|
|
| 133 |
"obj": obj_loss.item(),
|
| 134 |
"season": season_loss.item(),
|
| 135 |
"wear": wear_loss.item(),
|
|
|
|
| 136 |
"alignment": alignment_loss.item(),
|
| 137 |
"total": total.item(),
|
| 138 |
}
|
|
@@ -151,7 +163,7 @@ def train_epoch(
|
|
| 151 |
model.train()
|
| 152 |
heads.train()
|
| 153 |
total_loss = 0.0
|
| 154 |
-
totals = {"obj": 0.0, "season": 0.0, "wear": 0.0, "alignment": 0.0}
|
| 155 |
count = 0
|
| 156 |
|
| 157 |
for batch_idx, batch in enumerate(loader, start=1):
|
|
@@ -165,6 +177,8 @@ def train_epoch(
|
|
| 165 |
"seasonality": batch["target_sub_seasonality"].to(device),
|
| 166 |
"gender_profile": batch["target_sub_gender"].to(device),
|
| 167 |
"wearability": batch["target_sub_wearability"].to(device),
|
|
|
|
|
|
|
| 168 |
}
|
| 169 |
optimizer.zero_grad()
|
| 170 |
latent = model(tokens, physics, src_key_padding_mask) # (B, T, S, H)
|
|
@@ -182,11 +196,11 @@ def train_epoch(
|
|
| 182 |
for k in totals:
|
| 183 |
totals[k] += comps[k]
|
| 184 |
count += 1
|
| 185 |
-
weights = getattr(loss_balancer, "last_weights", [0.
|
| 186 |
logger.info(
|
| 187 |
-
"Batch %d | total=%.4f | obj=%.4f | season=%.4f | wear=%.4f |
|
| 188 |
-
batch_idx, comps["total"], comps["obj"], comps["season"], comps["wear"], comps["alignment"],
|
| 189 |
-
|
| 190 |
)
|
| 191 |
|
| 192 |
return {k: v / max(count, 1) for k, v in {**totals, "total": total_loss}.items()}
|
|
@@ -203,7 +217,7 @@ def validate(
|
|
| 203 |
model.eval()
|
| 204 |
heads.eval()
|
| 205 |
total_loss = 0.0
|
| 206 |
-
totals = {"obj": 0.0, "season": 0.0, "wear": 0.0, "alignment": 0.0}
|
| 207 |
count = 0
|
| 208 |
|
| 209 |
for batch in loader:
|
|
@@ -215,6 +229,8 @@ def validate(
|
|
| 215 |
"seasonality": batch["target_sub_seasonality"].to(device),
|
| 216 |
"gender_profile": batch["target_sub_gender"].to(device),
|
| 217 |
"wearability": batch["target_sub_wearability"].to(device),
|
|
|
|
|
|
|
| 218 |
}
|
| 219 |
latent = model(tokens, physics, src_key_padding_mask)
|
| 220 |
pred = heads(latent, physics, src_key_padding_mask)
|
|
@@ -234,8 +250,8 @@ def main():
|
|
| 234 |
parser = argparse.ArgumentParser(description="Train the PINO Physics-Informed Mixture Transformer")
|
| 235 |
parser.add_argument(
|
| 236 |
"--data",
|
| 237 |
-
default="data/
|
| 238 |
-
help="Path to the empirical dataset JSONL (default:
|
| 239 |
)
|
| 240 |
parser.add_argument("--epochs", type=int, default=5)
|
| 241 |
parser.add_argument("--batch-size", type=int, default=4)
|
|
@@ -349,9 +365,9 @@ def main():
|
|
| 349 |
|
| 350 |
# Multi-task loss balancer. Fix objective high so the pyramid head is not
|
| 351 |
# starved by the easier subjective tasks.
|
| 352 |
-
loss_weights = torch.tensor([0.
|
| 353 |
loss_balancer = AdaptiveLossBalancer(
|
| 354 |
-
num_tasks=
|
| 355 |
).to(device)
|
| 356 |
|
| 357 |
writer = SummaryWriter(log_dir=args.log_dir)
|
|
@@ -370,9 +386,9 @@ def main():
|
|
| 370 |
writer.add_scalar(f"{split}/{k}", v, epoch)
|
| 371 |
|
| 372 |
logger.info(
|
| 373 |
-
"Epoch %d/%d | train_total=%.4f | val_total=%.4f | obj=%.4f | season=%.4f | wear=%.4f | alignment=%.4f",
|
| 374 |
epoch, args.epochs, train_metrics["total"], val_metrics["total"],
|
| 375 |
-
val_metrics["obj"], val_metrics["season"], val_metrics["wear"], val_metrics["alignment"],
|
| 376 |
)
|
| 377 |
|
| 378 |
if val_metrics["total"] < best_val:
|
|
@@ -388,8 +404,8 @@ def main():
|
|
| 388 |
|
| 389 |
val_final_metrics = validate(model, heads, val_loader, device, loss_balancer)
|
| 390 |
logger.info(
|
| 391 |
-
"Final Val | total=%.4f | obj=%.4f | season=%.4f | wear=%.4f | alignment=%.4f",
|
| 392 |
-
val_final_metrics["total"], val_final_metrics["obj"], val_final_metrics["season"], val_final_metrics["wear"], val_final_metrics["alignment"],
|
| 393 |
)
|
| 394 |
writer.close()
|
| 395 |
return checkpoint_path
|
|
|
|
| 17 |
from torch.utils.tensorboard import SummaryWriter
|
| 18 |
|
| 19 |
from pino.heads import PIMTHeads
|
| 20 |
+
from pino.pimt_model import (
|
| 21 |
+
DEFAULT_EMBEDDING_DIM,
|
| 22 |
+
FragranceTrajectoryDataset,
|
| 23 |
+
PhysicsInformedMixtureTransformer,
|
| 24 |
+
objective_targets_to_pyramid,
|
| 25 |
+
)
|
| 26 |
from pino.thermo.losses import AdaptiveLossBalancer
|
| 27 |
from pino.upload_data import create_formula_disjoint_split_from_records
|
| 28 |
|
|
|
|
| 55 |
tokens = torch.zeros(bsz, max_molecules, DEFAULT_EMBEDDING_DIM, dtype=torch.float32)
|
| 56 |
physics = torch.zeros(bsz, max_timesteps, max_molecules, 2, dtype=torch.float32)
|
| 57 |
src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
|
| 58 |
+
target_obj = torch.zeros(bsz, 3, 138, dtype=torch.float32)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
target_sub_seasonality = torch.zeros(bsz, 4, dtype=torch.float32)
|
| 60 |
target_sub_gender = torch.zeros(bsz, dtype=torch.float32)
|
| 61 |
target_sub_wearability = torch.zeros(bsz, 2, dtype=torch.float32)
|
| 62 |
+
target_substantivity = torch.zeros(bsz, dtype=torch.float32)
|
| 63 |
+
target_substantivity_mask = torch.zeros(bsz, dtype=torch.float32)
|
| 64 |
genre_labels = torch.zeros(bsz, dtype=torch.int64)
|
| 65 |
|
| 66 |
for i, item in enumerate(batch):
|
|
|
|
| 69 |
tokens[i, :n_mol] = item["tokens"]
|
| 70 |
physics[i, :t_steps, :n_mol] = item["physics"]
|
| 71 |
src_key_padding_mask[i, :n_mol] = False
|
| 72 |
+
target_obj[i] = objective_targets_to_pyramid(item["target_obj"]).float()
|
| 73 |
sub = item["target_sub"]
|
| 74 |
target_sub_seasonality[i] = sub[[0,1,2,3]]
|
| 75 |
target_sub_gender[i] = sub[4]
|
| 76 |
target_sub_wearability[i] = sub[[5,6]]
|
| 77 |
+
target_substantivity[i] = item.get("target_substantivity", torch.tensor(0.0))
|
| 78 |
+
target_substantivity_mask[i] = item.get("target_substantivity_mask", torch.tensor(0.0))
|
| 79 |
genre_labels[i] = item.get("genre_label", 0)
|
| 80 |
|
| 81 |
# Force padding positions to a neutral log10_OAV sentinel so the Synergistic
|
|
|
|
| 90 |
"target_sub_seasonality": target_sub_seasonality,
|
| 91 |
"target_sub_gender": target_sub_gender,
|
| 92 |
"target_sub_wearability": target_sub_wearability,
|
| 93 |
+
"target_substantivity": target_substantivity,
|
| 94 |
+
"target_substantivity_mask": target_substantivity_mask,
|
| 95 |
"genre_label": genre_labels,
|
| 96 |
}
|
| 97 |
|
|
|
|
| 118 |
gender_loss = nn.functional.mse_loss(pred_sub["gender_profile"].squeeze(-1), target_sub["gender_profile"])
|
| 119 |
wear_loss = nn.functional.binary_cross_entropy_with_logits(pred_sub["wearability"], target_sub["wearability"])
|
| 120 |
wear_loss = wear_loss + gender_loss
|
| 121 |
+
sub_mask = target_sub.get("substantivity_mask")
|
| 122 |
+
if sub_mask is not None and float(sub_mask.sum().detach().cpu()) > 0:
|
| 123 |
+
sub_pred = pred_sub["substantivity"].squeeze(-1)
|
| 124 |
+
sub_loss = ((sub_pred - target_sub["substantivity"]) ** 2 * sub_mask).sum() / sub_mask.sum().clamp_min(1.0)
|
| 125 |
+
else:
|
| 126 |
+
sub_loss = pred_obj.new_tensor(0.0)
|
| 127 |
|
| 128 |
# Continuous cosine alignment between predicted 138-D descriptor profile and
|
| 129 |
# the mean of the true pyramid tiers over the three tiers. This keeps the
|
|
|
|
| 135 |
"obj": obj_loss,
|
| 136 |
"season": season_loss,
|
| 137 |
"wear": wear_loss,
|
| 138 |
+
"substantivity": sub_loss,
|
| 139 |
"alignment": alignment_loss,
|
| 140 |
}
|
| 141 |
|
|
|
|
| 144 |
"obj": obj_loss.item(),
|
| 145 |
"season": season_loss.item(),
|
| 146 |
"wear": wear_loss.item(),
|
| 147 |
+
"substantivity": sub_loss.item(),
|
| 148 |
"alignment": alignment_loss.item(),
|
| 149 |
"total": total.item(),
|
| 150 |
}
|
|
|
|
| 163 |
model.train()
|
| 164 |
heads.train()
|
| 165 |
total_loss = 0.0
|
| 166 |
+
totals = {"obj": 0.0, "season": 0.0, "wear": 0.0, "substantivity": 0.0, "alignment": 0.0}
|
| 167 |
count = 0
|
| 168 |
|
| 169 |
for batch_idx, batch in enumerate(loader, start=1):
|
|
|
|
| 177 |
"seasonality": batch["target_sub_seasonality"].to(device),
|
| 178 |
"gender_profile": batch["target_sub_gender"].to(device),
|
| 179 |
"wearability": batch["target_sub_wearability"].to(device),
|
| 180 |
+
"substantivity": batch["target_substantivity"].to(device),
|
| 181 |
+
"substantivity_mask": batch["target_substantivity_mask"].to(device),
|
| 182 |
}
|
| 183 |
optimizer.zero_grad()
|
| 184 |
latent = model(tokens, physics, src_key_padding_mask) # (B, T, S, H)
|
|
|
|
| 196 |
for k in totals:
|
| 197 |
totals[k] += comps[k]
|
| 198 |
count += 1
|
| 199 |
+
weights = getattr(loss_balancer, "last_weights", [0.35, 0.12, 0.12, 0.16, 0.25])
|
| 200 |
logger.info(
|
| 201 |
+
"Batch %d | total=%.4f | obj=%.4f | season=%.4f | wear=%.4f | substantivity=%.4f | alignment=%.4f | weights=%s",
|
| 202 |
+
batch_idx, comps["total"], comps["obj"], comps["season"], comps["wear"], comps["substantivity"], comps["alignment"],
|
| 203 |
+
[round(float(w), 3) for w in weights],
|
| 204 |
)
|
| 205 |
|
| 206 |
return {k: v / max(count, 1) for k, v in {**totals, "total": total_loss}.items()}
|
|
|
|
| 217 |
model.eval()
|
| 218 |
heads.eval()
|
| 219 |
total_loss = 0.0
|
| 220 |
+
totals = {"obj": 0.0, "season": 0.0, "wear": 0.0, "substantivity": 0.0, "alignment": 0.0}
|
| 221 |
count = 0
|
| 222 |
|
| 223 |
for batch in loader:
|
|
|
|
| 229 |
"seasonality": batch["target_sub_seasonality"].to(device),
|
| 230 |
"gender_profile": batch["target_sub_gender"].to(device),
|
| 231 |
"wearability": batch["target_sub_wearability"].to(device),
|
| 232 |
+
"substantivity": batch["target_substantivity"].to(device),
|
| 233 |
+
"substantivity_mask": batch["target_substantivity_mask"].to(device),
|
| 234 |
}
|
| 235 |
latent = model(tokens, physics, src_key_padding_mask)
|
| 236 |
pred = heads(latent, physics, src_key_padding_mask)
|
|
|
|
| 250 |
parser = argparse.ArgumentParser(description="Train the PINO Physics-Informed Mixture Transformer")
|
| 251 |
parser.add_argument(
|
| 252 |
"--data",
|
| 253 |
+
default="data/empirical_dataset_v9_plus_wisemoor.jsonl",
|
| 254 |
+
help="Path to the empirical dataset JSONL (default: v9 plus resolved WiseMoor formulas).",
|
| 255 |
)
|
| 256 |
parser.add_argument("--epochs", type=int, default=5)
|
| 257 |
parser.add_argument("--batch-size", type=int, default=4)
|
|
|
|
| 365 |
|
| 366 |
# Multi-task loss balancer. Fix objective high so the pyramid head is not
|
| 367 |
# starved by the easier subjective tasks.
|
| 368 |
+
loss_weights = torch.tensor([0.35, 0.12, 0.12, 0.16, 0.25])
|
| 369 |
loss_balancer = AdaptiveLossBalancer(
|
| 370 |
+
num_tasks=5, fixed_weights=loss_weights
|
| 371 |
).to(device)
|
| 372 |
|
| 373 |
writer = SummaryWriter(log_dir=args.log_dir)
|
|
|
|
| 386 |
writer.add_scalar(f"{split}/{k}", v, epoch)
|
| 387 |
|
| 388 |
logger.info(
|
| 389 |
+
"Epoch %d/%d | train_total=%.4f | val_total=%.4f | obj=%.4f | season=%.4f | wear=%.4f | substantivity=%.4f | alignment=%.4f",
|
| 390 |
epoch, args.epochs, train_metrics["total"], val_metrics["total"],
|
| 391 |
+
val_metrics["obj"], val_metrics["season"], val_metrics["wear"], val_metrics["substantivity"], val_metrics["alignment"],
|
| 392 |
)
|
| 393 |
|
| 394 |
if val_metrics["total"] < best_val:
|
|
|
|
| 404 |
|
| 405 |
val_final_metrics = validate(model, heads, val_loader, device, loss_balancer)
|
| 406 |
logger.info(
|
| 407 |
+
"Final Val | total=%.4f | obj=%.4f | season=%.4f | wear=%.4f | substantivity=%.4f | alignment=%.4f",
|
| 408 |
+
val_final_metrics["total"], val_final_metrics["obj"], val_final_metrics["season"], val_final_metrics["wear"], val_final_metrics["substantivity"], val_final_metrics["alignment"],
|
| 409 |
)
|
| 410 |
writer.close()
|
| 411 |
return checkpoint_path
|
tests/test_train_collate.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from pino.pimt_model import DEFAULT_EMBEDDING_DIM, objective_targets_to_pyramid
|
| 6 |
+
from pino.train import pad_trajectory_collate
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _item(target_obj: torch.Tensor, *, n_mol: int = 2, t_steps: int = 49) -> dict:
|
| 10 |
+
return {
|
| 11 |
+
"tokens": torch.ones(n_mol, DEFAULT_EMBEDDING_DIM),
|
| 12 |
+
"physics": torch.ones(t_steps, n_mol, 2),
|
| 13 |
+
"target_obj": target_obj,
|
| 14 |
+
"target_sub": torch.tensor([0.25, 0.25, 0.25, 0.25, 0.0, 0.5, 0.5]),
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_objective_targets_to_pyramid_keeps_native_pyramid() -> None:
|
| 19 |
+
targets = torch.rand(3, 138)
|
| 20 |
+
|
| 21 |
+
normalized = objective_targets_to_pyramid(targets)
|
| 22 |
+
|
| 23 |
+
assert normalized.shape == (3, 138)
|
| 24 |
+
assert torch.equal(normalized, targets)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_pad_trajectory_collate_normalizes_mixed_objective_target_shapes() -> None:
|
| 28 |
+
pyramid = torch.zeros(3, 138)
|
| 29 |
+
pyramid[0, 1] = 1.0
|
| 30 |
+
trajectory = torch.zeros(49, 138)
|
| 31 |
+
trajectory[0, 2] = 0.4
|
| 32 |
+
trajectory[20, 3] = 0.7
|
| 33 |
+
trajectory[-1, 4] = 1.0
|
| 34 |
+
|
| 35 |
+
batch = pad_trajectory_collate([_item(pyramid), _item(trajectory, n_mol=3)])
|
| 36 |
+
|
| 37 |
+
assert batch["target_obj"].shape == (2, 3, 138)
|
| 38 |
+
assert torch.equal(batch["target_obj"][0], pyramid)
|
| 39 |
+
assert batch["target_obj"][1, 0, 2] == 0.4
|
| 40 |
+
assert batch["target_obj"][1, 1, 3] == 0.7
|
| 41 |
+
assert batch["target_obj"][1, 2, 4] == 1.0
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_pad_trajectory_collate_normalizes_mixed_objective_target_shapes_when_legacy_first() -> None:
|
| 45 |
+
trajectory = torch.zeros(49, 138)
|
| 46 |
+
pyramid = torch.zeros(3, 138)
|
| 47 |
+
|
| 48 |
+
batch = pad_trajectory_collate([_item(trajectory), _item(pyramid)])
|
| 49 |
+
|
| 50 |
+
assert batch["target_obj"].shape == (2, 3, 138)
|