mattbitzesty commited on
Commit
82ddb20
·
unverified ·
1 Parent(s): 9ddcf86

v4: time-aware objective head, physics-derived v2 targets, Pyrfume vocab

Browse files

- Replace mean-pool ObjectiveOdorHead with SynergisticObjectiveHead that
attention-pools latent tokens using the per-token OAV physical weight.
- Generate empirical_dataset_v2.jsonl from OAV trajectories with top/heart/base
descriptor profiles aligned to the Pyrfume vocabulary.
- Switch train.py defaults to v2 dataset and pimt_v4.pt checkpoint.
- Update hf_train_job.py to download v2 dataset from pino-synthetic-dataset-v2.
- Update predict_shalimar.py to use pyrfume_vocabulary.json for descriptors.

.gitignore CHANGED
@@ -9,6 +9,9 @@ data/*.png
9
  data/*.jpg
10
  data/*.jpeg
11
  data/empirical_dataset_v1.jsonl
 
 
 
12
  logs/
13
  logs*/
14
 
 
9
  data/*.jpg
10
  data/*.jpeg
11
  data/empirical_dataset_v1.jsonl
12
+ data/empirical_dataset_v2.jsonl
13
+
14
+ # Logs
15
  logs/
16
  logs*/
17
 
data/pyrfume_descriptors_by_cas.json ADDED
The diff for this file is too large to render. See raw diff
 
data/pyrfume_vocabulary.json ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dimension": 138,
3
+ "vocabulary": [
4
+ "acidic",
5
+ "alcoholic",
6
+ "aldehydic",
7
+ "alliaceous",
8
+ "almond",
9
+ "amber",
10
+ "animal",
11
+ "anisic",
12
+ "apple",
13
+ "apricot",
14
+ "balsamic",
15
+ "banana",
16
+ "beefy",
17
+ "berry",
18
+ "bland",
19
+ "brandy",
20
+ "bready",
21
+ "brothy",
22
+ "brown",
23
+ "burnt",
24
+ "buttery",
25
+ "cabbage",
26
+ "camphoreous",
27
+ "caramellic",
28
+ "cedar",
29
+ "celery",
30
+ "chamomile",
31
+ "cheesy",
32
+ "cherry",
33
+ "chicken",
34
+ "chocolate",
35
+ "cinnamon",
36
+ "citrus",
37
+ "clean",
38
+ "cocoa",
39
+ "coconut",
40
+ "coffee",
41
+ "cognac",
42
+ "cooked",
43
+ "cooling",
44
+ "cortex",
45
+ "coumarinic",
46
+ "creamy",
47
+ "cucumber",
48
+ "dairy",
49
+ "dry",
50
+ "earthy",
51
+ "estery",
52
+ "ethereal",
53
+ "fatty",
54
+ "fermented",
55
+ "fishy",
56
+ "floral",
57
+ "fresh",
58
+ "fruity",
59
+ "garlic",
60
+ "gasoline",
61
+ "geranium",
62
+ "grape",
63
+ "grapefruit",
64
+ "grassy",
65
+ "green",
66
+ "hay",
67
+ "hazelnut",
68
+ "herbal",
69
+ "honey",
70
+ "horseradish",
71
+ "hyacinth",
72
+ "jasmin",
73
+ "jasmine",
74
+ "juicy",
75
+ "ketonic",
76
+ "lactonic",
77
+ "lavender",
78
+ "leafy",
79
+ "leathery",
80
+ "lemon",
81
+ "lily",
82
+ "malty",
83
+ "meaty",
84
+ "medicinal",
85
+ "melon",
86
+ "mentholic",
87
+ "metallic",
88
+ "mild",
89
+ "milky",
90
+ "mint",
91
+ "minty",
92
+ "muguet",
93
+ "mushroom",
94
+ "musk",
95
+ "musty",
96
+ "nutty",
97
+ "odorless",
98
+ "oily",
99
+ "onion",
100
+ "orange",
101
+ "orris",
102
+ "ozone",
103
+ "peach",
104
+ "pear",
105
+ "phenolic",
106
+ "pine",
107
+ "pineapple",
108
+ "plum",
109
+ "popcorn",
110
+ "potato",
111
+ "powdery",
112
+ "radish",
113
+ "raspberry",
114
+ "ripe",
115
+ "roasted",
116
+ "rose",
117
+ "rum",
118
+ "rummy",
119
+ "savory",
120
+ "sharp",
121
+ "smoky",
122
+ "soapy",
123
+ "solvent",
124
+ "sour",
125
+ "spicy",
126
+ "strawberry",
127
+ "sulfurous",
128
+ "sweet",
129
+ "tea",
130
+ "terpenic",
131
+ "tobacco",
132
+ "tomato",
133
+ "tropical",
134
+ "vanilla",
135
+ "vegetable",
136
+ "violet",
137
+ "warm",
138
+ "waxy",
139
+ "weedy",
140
+ "winey",
141
+ "woody"
142
+ ]
143
+ }
scripts/enrich_targets.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Enrich empirical_dataset_v1.jsonl with physics-derived time-varying targets.
3
+
4
+ For each record we compute how the OAV budget is distributed across top / heart /
5
+ base notes at every timestep. The objective target is then a time-varying blend
6
+ of the corresponding descriptor profiles (citrus/fresh/green for top notes,
7
+ floral/rose/jasmin for heart notes, woody/musk/amber for base notes). This
8
+ produces a target that is physically grounded in the diffusion trajectory and
9
+ varies over time because top notes fade and base notes emerge.
10
+
11
+ If Pyrfume annotations are available for an ingredient, the note class is
12
+ reconciled with the Pyrfume descriptor profile by using the ingredient's OAV
13
+ peak time as the primary signal.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import json
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ import numpy as np
23
+
24
+ DESCRIPTOR_DIM = 138
25
+
26
+ # Descriptor profiles for the three fragrance notes in the Pyrfume vocabulary.
27
+ TOP_PROFILE = ["citrus", "fresh", "fruity", "green", "aldehydic", "lemon", "grapefruit", "orange"]
28
+ HEART_PROFILE = ["floral", "rose", "jasmin", "jasmine", "muguet", "lily", "neroli", "ylang", "hyacinth", "lavender"]
29
+ BASE_PROFILE = ["woody", "musk", "amber", "vanilla", "balsamic", "sweet", "cedar", "leathery", "tobacco"]
30
+
31
+
32
+ def build_profile_vectors(vocab: list[str]) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
33
+ def _vec(words: list[str]) -> np.ndarray:
34
+ arr = np.zeros(DESCRIPTOR_DIM, dtype=np.float32)
35
+ for w in words:
36
+ if w in vocab:
37
+ arr[vocab.index(w)] = 1.0
38
+ return arr / (arr.sum() + 1e-8)
39
+ return _vec(TOP_PROFILE), _vec(HEART_PROFILE), _vec(BASE_PROFILE)
40
+
41
+
42
+ def classify_ingredients(oav: np.ndarray) -> list[str]:
43
+ """Classify each ingredient as top/heart/base by its OAV peak location."""
44
+ t_steps = oav.shape[0]
45
+ notes: list[str] = []
46
+ for s in range(oav.shape[1]):
47
+ traj = oav[:, s]
48
+ if traj.max() < 1e-12:
49
+ notes.append("heart")
50
+ continue
51
+ peak_t = int(np.argmax(traj))
52
+ frac = peak_t / (t_steps - 1) if t_steps > 1 else 0.5
53
+ if frac < 0.33:
54
+ notes.append("top")
55
+ elif frac > 0.66:
56
+ notes.append("base")
57
+ else:
58
+ notes.append("heart")
59
+ return notes
60
+
61
+
62
+ def enrich_record(
63
+ record: dict[str, Any],
64
+ top_vec: np.ndarray,
65
+ heart_vec: np.ndarray,
66
+ base_vec: np.ndarray,
67
+ ) -> dict[str, Any]:
68
+ record = dict(record)
69
+ formula = record.get("formula", [])
70
+ trajectory = record.get("trajectory", [])
71
+ if not formula or not trajectory:
72
+ return record
73
+
74
+ t_steps = len(trajectory)
75
+ s_ing = len(formula)
76
+ oav = np.zeros((t_steps, s_ing), dtype=np.float32)
77
+ for t, step in enumerate(trajectory):
78
+ oav_step = step.get("OAV", {})
79
+ for s, comp in enumerate(formula):
80
+ cas = comp.get("cas", "")
81
+ lookup_cas = cas[len("NATURAL:"):] if cas.startswith("NATURAL:") else cas
82
+ oav[t, s] = oav_step.get(lookup_cas, 0.0)
83
+
84
+ notes = classify_ingredients(oav)
85
+
86
+ # Build a time-varying descriptor matrix per ingredient.
87
+ ingredient_matrix = np.zeros((t_steps, s_ing, DESCRIPTOR_DIM), dtype=np.float32)
88
+ for s, note in enumerate(notes):
89
+ if note == "top":
90
+ profile = top_vec
91
+ elif note == "base":
92
+ profile = base_vec
93
+ else:
94
+ profile = heart_vec
95
+ # The ingredient's descriptor contribution is modulated by its OAV at
96
+ # each timestep so that it fades in/out of the mixture profile.
97
+ traj = oav[:, s]
98
+ max_oav = traj.max()
99
+ if max_oav < 1e-12:
100
+ weights = np.zeros(t_steps, dtype=np.float32)
101
+ else:
102
+ weights = traj / max_oav
103
+ ingredient_matrix[:, s, :] = weights[:, None] * profile[None, :]
104
+
105
+ # Mixture target per timestep is the sum over ingredients.
106
+ targets = ingredient_matrix.sum(axis=1) # (T, 138)
107
+ targets = np.clip(targets, 0.0, 1.0)
108
+
109
+ # Normalize each timestep to a unit-length descriptor direction while
110
+ # preserving the relative descriptor weights within the timestep.
111
+ norms = np.linalg.norm(targets, axis=1, keepdims=True)
112
+ targets = np.divide(targets, norms, out=np.zeros_like(targets), where=norms > 1e-8)
113
+
114
+ record["objective_targets"] = targets.astype(np.float32).tolist()
115
+ return record
116
+
117
+
118
+ def main() -> None:
119
+ parser = argparse.ArgumentParser()
120
+ parser.add_argument("--input", default="data/empirical_dataset_v1.jsonl")
121
+ parser.add_argument("--output", default="data/empirical_dataset_v2.jsonl")
122
+ parser.add_argument("--vocab", default="data/pyrfume_vocabulary.json")
123
+ args = parser.parse_args()
124
+
125
+ input_path = Path(args.input)
126
+ output_path = Path(args.output)
127
+
128
+ vocab_data = json.loads(Path(args.vocab).read_text())
129
+ vocab = vocab_data["vocabulary"] if isinstance(vocab_data, dict) else vocab_data
130
+ assert len(vocab) == DESCRIPTOR_DIM, f"Unexpected vocab size {len(vocab)}"
131
+ print(f"Loaded vocab: {len(vocab)} descriptors")
132
+
133
+ top_vec, heart_vec, base_vec = build_profile_vectors(vocab)
134
+
135
+ records = [json.loads(line) for line in input_path.open()]
136
+ print(f"Enriching {len(records)} records...")
137
+
138
+ out_file = output_path.open("w")
139
+ variance_list: list[float] = []
140
+ note_counts = {"top": 0, "heart": 0, "base": 0}
141
+ for rec in records:
142
+ enriched = enrich_record(rec, top_vec, heart_vec, base_vec)
143
+ obj = np.array(enriched["objective_targets"])
144
+ variance_list.append(float(obj.var(axis=0).mean()))
145
+ out_file.write(json.dumps(enriched, default=float) + "\n")
146
+
147
+ # Count notes for diagnostics.
148
+ t_steps = len(rec.get("trajectory", []))
149
+ if t_steps:
150
+ s_ing = len(rec.get("formula", []))
151
+ oav = np.zeros((t_steps, s_ing), dtype=np.float32)
152
+ for t, step in enumerate(rec["trajectory"]):
153
+ oav_step = step.get("OAV", {})
154
+ for s, comp in enumerate(rec["formula"]):
155
+ cas = comp.get("cas", "")
156
+ lookup_cas = cas[len("NATURAL:"):] if cas.startswith("NATURAL:") else cas
157
+ oav[t, s] = oav_step.get(lookup_cas, 0.0)
158
+ for note in classify_ingredients(oav):
159
+ note_counts[note] += 1
160
+ out_file.close()
161
+
162
+ variances = np.array(variance_list)
163
+ print(f"Wrote {len(records)} records to {output_path}")
164
+ print(f"Note distribution: {note_counts}")
165
+ print(f"Mean objective variance: {variances.mean():.6f}")
166
+ print(f"Median objective variance: {np.median(variances):.6f}")
167
+ print(f"Max objective variance: {variances.max():.6f}")
168
+ print(f"Fraction > 1e-3: {(variances > 1e-3).mean():.3f}")
169
+ print(f"Fraction > 1e-2: {(variances > 1e-2).mean():.3f}")
170
+ print(f"Fraction > 5e-2: {(variances > 5e-2).mean():.3f}")
171
+
172
+
173
+ if __name__ == "__main__":
174
+ main()
scripts/hf_train_job.py CHANGED
@@ -58,17 +58,17 @@ def hf_train_5epoch() -> None:
58
  token = os.environ.get("HF_TOKEN")
59
 
60
  # Allow mounted data path to override the repo default.
61
- data_path = Path(os.environ.get("HF_DATA_PATH", REPO_ROOT / "data" / "empirical_dataset_v1.jsonl"))
62
 
63
  if not data_path.exists() and token:
64
  # Download the dataset from the canonical dataset repository.
65
  from huggingface_hub import hf_hub_download
66
 
67
- print("📥 Downloading empirical bootstrap dataset from Hugging Face Hub...")
68
  data_path.parent.mkdir(parents=True, exist_ok=True)
69
  downloaded = hf_hub_download(
70
- repo_id="mattbitzesty/pino-synthetic-dataset",
71
- filename="empirical_dataset_v1.jsonl",
72
  repo_type="dataset",
73
  token=token,
74
  local_dir=str(data_path.parent),
@@ -77,7 +77,7 @@ def hf_train_5epoch() -> None:
77
  print(f" Dataset downloaded to {data_path}")
78
  elif not data_path.exists():
79
  # Allow the dataset to be mounted elsewhere in the container.
80
- data_path = Path("/data/empirical_dataset_v1.jsonl")
81
 
82
  OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
83
  LOG_DIR.mkdir(parents=True, exist_ok=True)
@@ -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_v3.pt",
126
  repo_id=repo_id,
127
  repo_type="model",
128
  )
 
58
  token = os.environ.get("HF_TOKEN")
59
 
60
  # Allow mounted data path to override the repo default.
61
+ data_path = Path(os.environ.get("HF_DATA_PATH", REPO_ROOT / "data" / "empirical_dataset_v2.jsonl"))
62
 
63
  if not data_path.exists() and token:
64
  # Download the dataset from the canonical dataset repository.
65
  from huggingface_hub import hf_hub_download
66
 
67
+ print("📥 Downloading empirical v2 dataset from Hugging Face Hub...")
68
  data_path.parent.mkdir(parents=True, exist_ok=True)
69
  downloaded = hf_hub_download(
70
+ repo_id="mattbitzesty/pino-synthetic-dataset-v2",
71
+ filename="empirical_dataset_v2.jsonl",
72
  repo_type="dataset",
73
  token=token,
74
  local_dir=str(data_path.parent),
 
77
  print(f" Dataset downloaded to {data_path}")
78
  elif not data_path.exists():
79
  # Allow the dataset to be mounted elsewhere in the container.
80
+ data_path = Path("/data/empirical_dataset_v2.jsonl")
81
 
82
  OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
83
  LOG_DIR.mkdir(parents=True, exist_ok=True)
 
122
  api = HfApi(token=token)
123
  api.upload_file(
124
  path_or_fileobj=str(checkpoint_path),
125
+ path_in_repo="pimt_v4.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_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
  )
@@ -312,7 +312,7 @@ def run_sensitivity_backtest(
312
 
313
  with torch.no_grad():
314
  latent = model(tokens, physics_t, src_key_padding_mask=mask)
315
- output = heads(latent)
316
  obj_last = output["objective"][:, -1, :].mean().item()
317
  wear = output["subjective"]["wearability"][0].cpu().numpy()
318
  results.append((delta, obj_last, wear[0], wear[1]))
@@ -393,7 +393,7 @@ def main() -> None:
393
  # Build model inputs with preserved natural oil tokens.
394
  engine = OlfactoryEmbeddingEngine()
395
  tokens = build_model_inputs(semantic_recipe, registry, engine)
396
- print(f"✅ Token tensor shape: {tokens.shape} (natural oils retained as discrete tokens)")
397
 
398
  # Aggregate physics from constituent trajectory back to token sequence.
399
  physics, const_to_token = aggregate_physics_for_tokens(result["trajectory"], semantic_recipe)
@@ -403,9 +403,10 @@ def main() -> None:
403
  mask = torch.zeros(1, tokens.size(1), dtype=torch.bool)
404
 
405
  model, heads, device = load_pimt_checkpoint()
 
406
  with torch.no_grad():
407
  latent = model(tokens.to(device), physics_t.to(device), src_key_padding_mask=mask.to(device))
408
- output = heads(latent)
409
 
410
  objective = output["objective"].cpu().numpy() # (1, T, 138)
411
  sub = output["subjective"]
@@ -413,8 +414,9 @@ def main() -> None:
413
  gender = sub["gender_profile"].cpu().numpy() # (1, 1)
414
  wearability = sub["wearability"].cpu().numpy() # (1, 2)
415
 
416
- vocab_path = Path("data/odor_descriptor_vocab.json")
417
- vocab = json.loads(vocab_path.read_text()) if vocab_path.exists() else [f"dim_{i}" for i in range(138)]
 
418
 
419
  # Top descriptors at phases.
420
  phases = ["top (0 min)", "early dry (2 h)", "heart (4 h)", "late dry (8 h)"]
 
218
 
219
 
220
  def load_pimt_checkpoint() -> tuple[PhysicsInformedMixtureTransformer, PIMTHeads, torch.device]:
221
+ checkpoint_path = Path("models/pimt_v4.pt")
222
  if not checkpoint_path.exists():
223
  hf_hub_download(
224
  repo_id="mattbitzesty/pino-pimt-checkpoint",
225
+ filename="pimt_v4.pt",
226
  repo_type="model",
227
  local_dir="models",
228
  )
 
312
 
313
  with torch.no_grad():
314
  latent = model(tokens, physics_t, src_key_padding_mask=mask)
315
+ output = heads(latent, states=physics_t, src_key_padding_mask=mask)
316
  obj_last = output["objective"][:, -1, :].mean().item()
317
  wear = output["subjective"]["wearability"][0].cpu().numpy()
318
  results.append((delta, obj_last, wear[0], wear[1]))
 
393
  # Build model inputs with preserved natural oil tokens.
394
  engine = OlfactoryEmbeddingEngine()
395
  tokens = build_model_inputs(semantic_recipe, registry, engine)
396
+ print("✅ Token tensor shape:", tokens.shape, "(natural oils retained as discrete tokens)")
397
 
398
  # Aggregate physics from constituent trajectory back to token sequence.
399
  physics, const_to_token = aggregate_physics_for_tokens(result["trajectory"], semantic_recipe)
 
403
  mask = torch.zeros(1, tokens.size(1), dtype=torch.bool)
404
 
405
  model, heads, device = load_pimt_checkpoint()
406
+
407
  with torch.no_grad():
408
  latent = model(tokens.to(device), physics_t.to(device), src_key_padding_mask=mask.to(device))
409
+ output = heads(latent, states=physics_t.to(device), src_key_padding_mask=mask.to(device))
410
 
411
  objective = output["objective"].cpu().numpy() # (1, T, 138)
412
  sub = output["subjective"]
 
414
  gender = sub["gender_profile"].cpu().numpy() # (1, 1)
415
  wearability = sub["wearability"].cpu().numpy() # (1, 2)
416
 
417
+ vocab_path = Path("data/pyrfume_vocabulary.json")
418
+ vocab_data = json.loads(vocab_path.read_text())
419
+ vocab = vocab_data["vocabulary"] if isinstance(vocab_data, dict) else vocab_data
420
 
421
  # Top descriptors at phases.
422
  phases = ["top (0 min)", "early dry (2 h)", "heart (4 h)", "late dry (8 h)"]
src/pino/heads.py CHANGED
@@ -2,32 +2,77 @@ from __future__ import annotations
2
 
3
  import torch
4
  import torch.nn as nn
 
5
 
6
 
7
- class ObjectiveOdorHead(nn.Module):
8
  """
9
- Head A: time-resolved objective odor profile.
10
- Maps each timestep's latent tokens to a 138-dimensional Sigmoid-activated
11
- odor descriptor vector.
 
 
 
 
12
  """
13
 
14
- def __init__(self, hidden_dim: int = 256, output_dim: int = 138) -> None:
 
 
 
 
 
15
  super().__init__()
16
  self.output_dim = output_dim
17
- self.mlp = nn.Sequential(
18
- nn.Linear(hidden_dim, hidden_dim),
 
 
 
19
  nn.ReLU(),
20
- nn.Dropout(0.1),
21
  nn.Linear(hidden_dim, output_dim),
22
  nn.Sigmoid(),
23
  )
24
 
25
- def forward(self, x: torch.Tensor) -> torch.Tensor:
 
 
 
 
 
26
  """
27
- x: (B, T, S, hidden_dim)
 
 
28
  Returns: (B, T, output_dim)
29
  """
30
- return self.mlp(x.mean(dim=2)) # pool over ingredient sequence
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
 
33
  class SubjectiveSemanticHead(nn.Module):
@@ -105,17 +150,26 @@ class PIMTHeads(nn.Module):
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
  }
 
2
 
3
  import torch
4
  import torch.nn as nn
5
+ import torch.nn.functional as F
6
 
7
 
8
+ class SynergisticObjectiveHead(nn.Module):
9
  """
10
+ Non-linear, attention-guided objective odor head.
11
+
12
+ The head learns a per-token attention distribution over ingredients using
13
+ both the encoder representation and the real-time OAV-derived physical
14
+ weight. The attention-pooled latent is then projected to a 138-D
15
+ descriptor profile. This prevents the time-varying signal from being
16
+ drowned out by mean-pooling over the full recipe.
17
  """
18
 
19
+ def __init__(
20
+ self,
21
+ embedding_dim: int = 256,
22
+ hidden_dim: int = 128,
23
+ output_dim: int = 138,
24
+ ) -> None:
25
  super().__init__()
26
  self.output_dim = output_dim
27
+ # Ingests token embedding + normalized OAV weight.
28
+ self.attention_query = nn.Linear(embedding_dim + 1, 1)
29
+ # Non-linear projection to handle emergent compound properties.
30
+ self.final_mlp = nn.Sequential(
31
+ nn.Linear(embedding_dim, hidden_dim),
32
  nn.ReLU(),
 
33
  nn.Linear(hidden_dim, output_dim),
34
  nn.Sigmoid(),
35
  )
36
 
37
+ def forward(
38
+ self,
39
+ x: torch.Tensor,
40
+ states: torch.Tensor,
41
+ src_key_padding_mask: torch.Tensor | None = None,
42
+ ) -> torch.Tensor:
43
  """
44
+ x: (B, T, S, embedding_dim)
45
+ states: (B, T, S, 2) -> [x_liquid, log10_OAV]
46
+ src_key_padding_mask: (B, S) bool mask where True marks padding.
47
  Returns: (B, T, output_dim)
48
  """
49
+ # 1. Safely extract raw OAV proportions from the log10 physics track.
50
+ log10_oav = states[..., 1:2] # (B, T, S, 1)
51
+ raw_oav = torch.pow(10.0, log10_oav)
52
+ # Zero out safe floors so dead ingredients don't pollute attention.
53
+ raw_oav = torch.where(log10_oav <= -5.9, torch.zeros_like(raw_oav), raw_oav)
54
+
55
+ # 2. Compute relative headspace impact fractions per timestep.
56
+ if src_key_padding_mask is not None:
57
+ # Zero out padding positions before normalizing.
58
+ pad_mask = src_key_padding_mask.unsqueeze(1).unsqueeze(-1) # (B, 1, S, 1)
59
+ raw_oav = raw_oav.masked_fill(pad_mask, 0.0)
60
+ total_oav = raw_oav.sum(dim=2, keepdim=True) + 1e-8
61
+ physical_weights = raw_oav / total_oav # (B, T, S, 1)
62
+
63
+ # 3. Compute non-linear synergistic pooling weights.
64
+ context = torch.cat([x, physical_weights], dim=-1) # (B, T, S, E+1)
65
+ attn_scores = self.attention_query(context) # (B, T, S, 1)
66
+
67
+ if src_key_padding_mask is not None:
68
+ # Force padded positions to a very negative attention score.
69
+ attn_scores = attn_scores.masked_fill(pad_mask, -1e9)
70
+
71
+ attn_weights = F.softmax(attn_scores, dim=2) # Softmax over ingredients.
72
+
73
+ # 4. Attention-pool the latent space and project to final descriptors.
74
+ pooled_latent = (x * attn_weights).sum(dim=2) # (B, T, E)
75
+ return self.final_mlp(pooled_latent) # (B, T, output_dim)
76
 
77
 
78
  class SubjectiveSemanticHead(nn.Module):
 
150
  num_classes_sub: int = 7,
151
  ) -> None:
152
  super().__init__()
153
+ self.objective = SynergisticObjectiveHead(hidden_dim, hidden_dim=128, output_dim=objective_dim)
154
  self.subjective = SubjectiveSemanticHead(hidden_dim, num_classes_sub)
155
  self.alignment = ContinuousAlignmentHead(hidden_dim, objective_dim)
156
 
157
+ def forward(
158
+ self,
159
+ x: torch.Tensor,
160
+ states: torch.Tensor | None = None,
161
+ src_key_padding_mask: torch.Tensor | None = None,
162
+ ) -> dict[str, torch.Tensor]:
163
  """
164
  x: (B, T, S, hidden_dim)
165
+ states: optional (B, T, S, 2) physics states for the objective head.
166
+ src_key_padding_mask: optional (B, S) bool mask, True for padding.
167
  Returns dict with 'objective', 'subjective', and 'alignment' outputs.
168
  """
169
+ if states is None:
170
+ states = x[..., :2].detach().clone()
171
  return {
172
+ "objective": self.objective(x, states, src_key_padding_mask=src_key_padding_mask), # (B, T, 138)
173
  "subjective": self.subjective(x), # (B, 7)
174
  "alignment": self.alignment(x), # (B, 138)
175
  }
src/pino/train.py CHANGED
@@ -162,7 +162,8 @@ def train_epoch(
162
  }
163
  optimizer.zero_grad()
164
  latent = model(tokens, physics, src_key_padding_mask) # (B, T, S, H)
165
- pred = heads(latent)
 
166
  loss, comps = multitask_loss(
167
  pred["objective"], target_obj, pred["subjective"], target_sub,
168
  pred["alignment"], loss_balancer,
@@ -210,7 +211,7 @@ def validate(
210
  "wearability": batch["target_sub_wearability"].to(device),
211
  }
212
  latent = model(tokens, physics, src_key_padding_mask)
213
- pred = heads(latent)
214
  loss, comps = multitask_loss(
215
  pred["objective"], target_obj, pred["subjective"], target_sub,
216
  pred["alignment"], loss_balancer,
@@ -227,8 +228,8 @@ def main():
227
  parser = argparse.ArgumentParser(description="Train the PINO Physics-Informed Mixture Transformer")
228
  parser.add_argument(
229
  "--data",
230
- default="data/empirical_dataset_v1.jsonl",
231
- help="Path to the empirical bootstrap dataset (default: data/empirical_dataset_v1.jsonl)",
232
  )
233
  parser.add_argument("--epochs", type=int, default=5)
234
  parser.add_argument("--batch-size", type=int, default=4)
@@ -266,7 +267,7 @@ def main():
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
 
 
162
  }
163
  optimizer.zero_grad()
164
  latent = model(tokens, physics, src_key_padding_mask) # (B, T, S, H)
165
+ # Compute attention-guided objective predictions using the physics states.
166
+ pred = heads(latent, states=physics, src_key_padding_mask=src_key_padding_mask)
167
  loss, comps = multitask_loss(
168
  pred["objective"], target_obj, pred["subjective"], target_sub,
169
  pred["alignment"], loss_balancer,
 
211
  "wearability": batch["target_sub_wearability"].to(device),
212
  }
213
  latent = model(tokens, physics, src_key_padding_mask)
214
+ pred = heads(latent, states=physics, src_key_padding_mask=src_key_padding_mask)
215
  loss, comps = multitask_loss(
216
  pred["objective"], target_obj, pred["subjective"], target_sub,
217
  pred["alignment"], loss_balancer,
 
228
  parser = argparse.ArgumentParser(description="Train the PINO Physics-Informed Mixture Transformer")
229
  parser.add_argument(
230
  "--data",
231
+ default="data/empirical_dataset_v2.jsonl",
232
+ help="Path to the empirical dataset JSONL (default: v2 physics-derived targets).",
233
  )
234
  parser.add_argument("--epochs", type=int, default=5)
235
  parser.add_argument("--batch-size", type=int, default=4)
 
267
  "max_batches_per_epoch": None,
268
  "lr": args.lr,
269
  "weight_decay": 1e-2,
270
+ "checkpoint_name": "pimt_v4.pt",
271
  }
272
  logger.info("Configuration: %s", cfg)
273