mattbitzesty commited on
Commit
e22b587
·
verified ·
1 Parent(s): 34f4fdb

round-7: disjoint encoder pipeline (scripts/train_disjoint_encoder.py)

Browse files
Files changed (1) hide show
  1. scripts/train_disjoint_encoder.py +700 -0
scripts/train_disjoint_encoder.py ADDED
@@ -0,0 +1,700 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Self-contained MPNN odor encoder for the PINO disjoint corpus.
3
+
4
+ Trains a pure-PyTorch message-passing neural network (no torch-geometric / DGL)
5
+ on the OpenPOM-style 138-task multi-label corpus assembled at
6
+ ``artifacts/disjoint_encoder/openpom_curated_disjoint.csv`` (3,662 molecules with
7
+ all 1,321 benchmark-overlapping molecules removed — see
8
+ ``assembly_summary.json`` for the exclusion audit).
9
+
10
+ The model is the OpenPOM-style graph encoder requested by the PINO evaluation
11
+ reviewer: an MPNN whose 256-d penultimate embedding serves as a drop-in
12
+ structural representation of each molecule.
13
+
14
+ Atom features (from RDKit)
15
+ atomic number, degree, formal charge, hybridization, aromaticity,
16
+ implicit+explicit H count, in-ring flag.
17
+
18
+ Bond features
19
+ bond type, conjugation, ring membership, stereo.
20
+
21
+ Architecture
22
+ atom embedding -> 3 message-passing steps (GRU-style updates)
23
+ -> attention readout -> MLP -> 256-d penultimate -> 138-d sigmoid multi-task head.
24
+
25
+ CLI
26
+ --csv CSV Input OpenPOM-style CSV (default disjoint corpus).
27
+ --epochs N Default 60.
28
+ --batch-size N Default 64.
29
+ --lr FLOAT Default 1e-3.
30
+ --seed INT Default 2026.
31
+ --embed-out PATH Write per-molecule 256-d embeddings for ALL rows as .npy + index JSON {ids, smiles}.
32
+ --checkpoint-out PATH Save trained model weights (state_dict + config) as .pt.
33
+ --smoke Run 3 epochs on 64 molecules CPU and exit 0.
34
+ --embed-smiles-csv PATH Optional: a CSV of SMILES to embed with a loaded
35
+ checkpoint instead of training (column: nonStereoSMILES or smiles).
36
+
37
+ Dependencies: torch, rdkit, numpy, scikit-learn. No PINO package imports — this
38
+ script runs standalone in a bare container with only those four packages.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import argparse
44
+ import csv
45
+ import json
46
+ import os
47
+ import random
48
+ import sys
49
+ from typing import List, Optional, Tuple
50
+
51
+ import numpy as np
52
+ import torch
53
+ import torch.nn as nn
54
+ import torch.nn.functional as F
55
+ from rdkit import Chem
56
+ from rdkit.Chem import HybridizationType
57
+ from sklearn.metrics import roc_auc_score
58
+
59
+ # ---------------------------------------------------------------------------
60
+ # Reproducibility
61
+ # ---------------------------------------------------------------------------
62
+
63
+ def set_seed(seed: int) -> None:
64
+ """Seed python / numpy / torch for deterministic training."""
65
+ random.seed(seed)
66
+ np.random.seed(seed)
67
+ torch.manual_seed(seed)
68
+ if torch.cuda.is_available():
69
+ torch.cuda.manual_seed_all(seed)
70
+
71
+
72
+ # ---------------------------------------------------------------------------
73
+ # Feature featurization (RDKit -> fixed-size tensors)
74
+ # ---------------------------------------------------------------------------
75
+
76
+ # Hybridization enum values we one-hot encode (SP, SP2, SP3, SP3D, SP3D2, OTHER).
77
+ _HYBRID_VALUES = [
78
+ HybridizationType.S,
79
+ HybridizationType.SP,
80
+ HybridizationType.SP2,
81
+ HybridizationType.SP3,
82
+ HybridizationType.SP3D,
83
+ HybridizationType.SP3D2,
84
+ ]
85
+ _HYBRID_INDEX = {h: i for i, h in enumerate(_HYBRID_VALUES)}
86
+
87
+ # Bond type one-hot: SINGLE, DOUBLE, TRIPLE, AROMATIC, OTHER.
88
+ _BOND_TYPES = [
89
+ Chem.BondType.SINGLE,
90
+ Chem.BondType.DOUBLE,
91
+ Chem.BondType.TRIPLE,
92
+ Chem.BondType.AROMATIC,
93
+ ]
94
+ _BOND_INDEX = {b: i for i, b in enumerate(_BOND_TYPES)}
95
+
96
+ # Stereo one-hot: NONE, E, Z, OTHER.
97
+ _BOND_STEREOS = [
98
+ Chem.BondStereo.STEREONONE,
99
+ Chem.BondStereo.STEREOE,
100
+ Chem.BondStereo.STEREOZ,
101
+ ]
102
+ _BOND_STEREO_INDEX = {s: i for i, s in enumerate(_BOND_STEREOS)}
103
+
104
+ ATOM_FEATURE_DIM = (
105
+ 1 # atomic number
106
+ + 1 # degree
107
+ + 1 # formal charge
108
+ + (len(_HYBRID_VALUES) + 1) # hybridization one-hot + "other"
109
+ + 1 # aromaticity
110
+ + 1 # total H count
111
+ + 1 # in ring
112
+ ) # = 13
113
+
114
+ BOND_FEATURE_DIM = (
115
+ (len(_BOND_TYPES) + 1) # bond type one-hot + "other"
116
+ + 1 # conjugated
117
+ + 1 # in ring
118
+ + (len(_BOND_STEREOS) + 1) # stereo one-hot + "other"
119
+ ) # = 11
120
+
121
+
122
+ def atom_features(a) -> np.ndarray:
123
+ fe = np.zeros(ATOM_FEATURE_DIM, dtype=np.float32)
124
+ off = 0
125
+ fe[off] = a.GetAtomicNum(); off += 1
126
+ fe[off] = a.GetDegree(); off += 1
127
+ fe[off] = a.GetFormalCharge(); off += 1
128
+ h = a.GetHybridization()
129
+ if h in _HYBRID_INDEX:
130
+ fe[off + _HYBRID_INDEX[h]] = 1.0
131
+ else:
132
+ fe[off + len(_HYBRID_VALUES)] = 1.0 # "other"
133
+ off += len(_HYBRID_VALUES) + 1
134
+ fe[off] = 1.0 if a.GetIsAromatic() else 0.0; off += 1
135
+ fe[off] = a.GetTotalNumHs(); off += 1
136
+ fe[off] = 1.0 if a.IsInRing() else 0.0; off += 1
137
+ return fe
138
+
139
+
140
+ def bond_features(b) -> np.ndarray:
141
+ fe = np.zeros(BOND_FEATURE_DIM, dtype=np.float32)
142
+ off = 0
143
+ bt = b.GetBondType()
144
+ if bt in _BOND_INDEX:
145
+ fe[off + _BOND_INDEX[bt]] = 1.0
146
+ else:
147
+ fe[off + len(_BOND_TYPES)] = 1.0 # "other"
148
+ off += len(_BOND_TYPES) + 1
149
+ fe[off] = 1.0 if b.GetIsConjugated() else 0.0; off += 1
150
+ fe[off] = 1.0 if b.IsInRing() else 0.0; off += 1
151
+ st = b.GetStereo()
152
+ if st in _BOND_STEREO_INDEX:
153
+ fe[off + _BOND_STEREO_INDEX[st]] = 1.0
154
+ else:
155
+ fe[off + len(_BOND_STEREOS)] = 1.0 # "other"
156
+ off += len(_BOND_STEREOS) + 1
157
+ return fe
158
+
159
+
160
+ class MolGraph:
161
+ """Featurized single molecule, stored as numpy arrays (no torch dependency).
162
+
163
+ Edges are stored undirected (both directions) to support standard MPNN.
164
+ """
165
+
166
+ __slots__ = ("n_atoms", "x", "edge_index", "edge_attr")
167
+
168
+ def __init__(self, smiles: str) -> None:
169
+ mol = Chem.MolFromSmiles(smiles)
170
+ if mol is None:
171
+ raise ValueError(f"RDKit could not parse SMILES: {smiles!r}")
172
+ n = mol.GetNumAtoms()
173
+ if n == 0:
174
+ raise ValueError(f"Empty molecule (0 atoms): {smiles!r}")
175
+
176
+ x = np.stack([atom_features(a) for a in mol.GetAtoms()], axis=0)
177
+
178
+ src: List[int] = []
179
+ dst: List[int] = []
180
+ ea: List[np.ndarray] = []
181
+ for b in mol.GetBonds():
182
+ i, j = b.GetBeginAtomIdx(), b.GetEndAtomIdx()
183
+ bf = bond_features(b)
184
+ src.append(i); dst.append(j); ea.append(bf)
185
+ src.append(j); dst.append(i); ea.append(bf)
186
+
187
+ if ea:
188
+ edge_index = np.stack(
189
+ [np.asarray(src, dtype=np.int64), np.asarray(dst, dtype=np.int64)],
190
+ axis=0,
191
+ )
192
+ edge_attr = np.stack(ea, axis=0)
193
+ else:
194
+ # Isolated atom (e.g. noble gas): no edges — keep empty arrays.
195
+ edge_index = np.zeros((2, 0), dtype=np.int64)
196
+ edge_attr = np.zeros((0, BOND_FEATURE_DIM), dtype=np.float32)
197
+
198
+ self.n_atoms = n
199
+ self.x = x
200
+ self.edge_index = edge_index
201
+ self.edge_attr = edge_attr
202
+
203
+
204
+ # ---------------------------------------------------------------------------
205
+ # Batching — collate a list of MolGraphs into a padded block-diagonal batch
206
+ # ---------------------------------------------------------------------------
207
+
208
+ def collate_batch(graphs: List[MolGraph], labels: Optional[np.ndarray] = None):
209
+ """Pack a list of MolGraphs into a single block-diagonal graph.
210
+
211
+ Returns dict with tensors:
212
+ x [N, ATOM_FEATURE_DIM]
213
+ edge_index[2, E]
214
+ edge_attr [E, BOND_FEATURE_DIM]
215
+ batch [N] graph index of each atom
216
+ n_graphs int
217
+ labels [B, T] or None
218
+ """
219
+ xs, eis, eas, batch_idx = [], [], [], []
220
+ offset = 0
221
+ for gi, g in enumerate(graphs):
222
+ xs.append(g.x)
223
+ batch_idx.append(np.full(g.n_atoms, gi, dtype=np.int64))
224
+ if g.edge_index.shape[1] > 0:
225
+ eis.append(g.edge_index + offset)
226
+ eas.append(g.edge_attr)
227
+ offset += g.n_atoms
228
+
229
+ x = np.concatenate(xs, axis=0)
230
+ batch = np.concatenate(batch_idx, axis=0)
231
+ if eis:
232
+ edge_index = np.concatenate(eis, axis=1)
233
+ edge_attr = np.concatenate(eas, axis=0)
234
+ else:
235
+ edge_index = np.zeros((2, 0), dtype=np.int64)
236
+ edge_attr = np.zeros((0, BOND_FEATURE_DIM), dtype=np.float32)
237
+
238
+ out = {
239
+ "x": torch.from_numpy(x),
240
+ "edge_index": torch.from_numpy(edge_index),
241
+ "edge_attr": torch.from_numpy(edge_attr),
242
+ "batch": torch.from_numpy(batch),
243
+ "n_graphs": len(graphs),
244
+ }
245
+ if labels is not None:
246
+ out["labels"] = torch.from_numpy(labels.astype(np.float32))
247
+ return out
248
+
249
+
250
+ # ---------------------------------------------------------------------------
251
+ # Model: MPNN with GRU updates + attention readout
252
+ # ---------------------------------------------------------------------------
253
+
254
+ class MessagePassingLayer(nn.Module):
255
+ """One MPNN step: messages = sum_j MLP_e([h_i, h_j, e_ij]); update via GRU."""
256
+
257
+ def __init__(self, hidden_dim: int, edge_dim: int, dropout: float = 0.1):
258
+ super().__init__()
259
+ self.message_fn = nn.Sequential(
260
+ nn.Linear(hidden_dim * 2 + edge_dim, hidden_dim),
261
+ nn.ReLU(),
262
+ nn.Linear(hidden_dim, hidden_dim),
263
+ )
264
+ self.gru = nn.GRUCell(hidden_dim, hidden_dim)
265
+ self.dropout = nn.Dropout(dropout)
266
+
267
+ def forward(
268
+ self,
269
+ x: torch.Tensor, # [N, H]
270
+ edge_index: torch.Tensor, # [2, E]
271
+ edge_attr: torch.Tensor, # [E, E]
272
+ ) -> torch.Tensor:
273
+ if edge_index.shape[1] == 0:
274
+ return x
275
+ src, dst = edge_index[0], edge_index[1]
276
+ msg_in = torch.cat([x[src], x[dst], edge_attr], dim=-1)
277
+ messages = self.message_fn(msg_in)
278
+ # Aggregate via scatter-add.
279
+ agg = torch.zeros_like(x)
280
+ agg.index_add_(0, dst, messages)
281
+ agg = self.dropout(agg)
282
+ # GRU update (treat agg as input, x as hidden).
283
+ return self.gru(agg, x)
284
+
285
+
286
+ class AttentionReadout(nn.Module):
287
+ """Soft attention pooling over atom embeddings per molecule."""
288
+
289
+ def __init__(self, hidden_dim: int):
290
+ super().__init__()
291
+ self.attn = nn.Sequential(
292
+ nn.Linear(hidden_dim, hidden_dim),
293
+ nn.Tanh(),
294
+ nn.Linear(hidden_dim, 1),
295
+ )
296
+
297
+ def forward(self, x: torch.Tensor, batch: torch.Tensor, n_graphs: int) -> torch.Tensor:
298
+ scores = self.attn(x).squeeze(-1) # [N]
299
+ out = torch.zeros(n_graphs, x.size(-1), device=x.device, dtype=x.dtype)
300
+ denom = torch.zeros(n_graphs, device=x.device, dtype=x.dtype)
301
+ # Softmax within each graph via scatter.
302
+ scores_exp = torch.exp(scores - scores.max())
303
+ denom.index_add_(0, batch, scores_exp)
304
+ denom = denom.clamp(min=1e-9)
305
+ weights = scores_exp / denom[batch] # [N]
306
+ weighted = x * weights.unsqueeze(-1)
307
+ out.index_add_(0, batch, weighted)
308
+ return out
309
+
310
+
311
+ class MPNNEncoder(nn.Module):
312
+ """Full MPNN: embed atoms -> 3 MP steps -> attention readout -> MLP head.
313
+
314
+ Exposes ``penultimate_features`` which returns the 256-d embedding used as
315
+ the molecular structural representation.
316
+ """
317
+
318
+ def __init__(
319
+ self,
320
+ atom_dim: int = ATOM_FEATURE_DIM,
321
+ bond_dim: int = BOND_FEATURE_DIM,
322
+ hidden_dim: int = 128,
323
+ n_steps: int = 3,
324
+ embed_dim: int = 256,
325
+ n_tasks: int = 138,
326
+ dropout: float = 0.1,
327
+ ):
328
+ super().__init__()
329
+ self.atom_embed = nn.Sequential(
330
+ nn.Linear(atom_dim, hidden_dim),
331
+ nn.ReLU(),
332
+ nn.Dropout(dropout),
333
+ )
334
+ self.mp_layers = nn.ModuleList(
335
+ [MessagePassingLayer(hidden_dim, bond_dim, dropout) for _ in range(n_steps)]
336
+ )
337
+ self.readout = AttentionReadout(hidden_dim)
338
+ # MLP -> 256-d penultimate embedding
339
+ self.mlp = nn.Sequential(
340
+ nn.Linear(hidden_dim, hidden_dim),
341
+ nn.ReLU(),
342
+ nn.Dropout(dropout),
343
+ )
344
+ self.penultimate = nn.Linear(hidden_dim, embed_dim)
345
+ self.head = nn.Linear(embed_dim, n_tasks)
346
+ self.embed_dim = embed_dim
347
+ self.n_tasks = n_tasks
348
+
349
+ def penultimate_features(self, batch: dict) -> torch.Tensor:
350
+ x = self.atom_embed(batch["x"])
351
+ for layer in self.mp_layers:
352
+ x = layer(x, batch["edge_index"], batch["edge_attr"])
353
+ pooled = self.readout(x, batch["batch"], batch["n_graphs"])
354
+ mlp_out = self.mlp(pooled)
355
+ return self.penultimate(mlp_out) # [B, embed_dim]
356
+
357
+ def forward(self, batch: dict) -> torch.Tensor:
358
+ emb = self.penultimate_features(batch)
359
+ return self.head(emb) # logits [B, n_tasks]
360
+
361
+
362
+ # ---------------------------------------------------------------------------
363
+ # Data loading
364
+ # ---------------------------------------------------------------------------
365
+
366
+ def load_csv(path: str) -> Tuple[List[str], np.ndarray, List[str]]:
367
+ """Load the OpenPOM-style CSV. Returns (smiles_list, labels[n,138], label_names).
368
+
369
+ Expected columns: nonStereoSMILES, descriptors, <138 label columns>.
370
+ """
371
+ with open(path, newline="") as f:
372
+ reader = csv.reader(f)
373
+ header = next(reader)
374
+ rows = list(reader)
375
+ if header[0] != "nonStereoSMILES":
376
+ raise ValueError(f"Expected first column 'nonStereoSMILES', got {header[0]!r}")
377
+ label_names = header[2:]
378
+ n_labels = len(label_names)
379
+ smiles_list: List[str] = []
380
+ labels = np.zeros((len(rows), n_labels), dtype=np.float32)
381
+ for i, row in enumerate(rows):
382
+ smiles_list.append(row[0].strip())
383
+ for j in range(n_labels):
384
+ v = row[2 + j].strip()
385
+ labels[i, j] = 1.0 if v == "1" else 0.0
386
+ return smiles_list, labels, label_names
387
+
388
+
389
+ def featurize_all(smiles_list: List[str], verbose: bool = False) -> List[Optional[MolGraph]]:
390
+ graphs: List[Optional[MolGraph]] = []
391
+ bad = 0
392
+ for s in smiles_list:
393
+ try:
394
+ graphs.append(MolGraph(s))
395
+ except Exception:
396
+ graphs.append(None)
397
+ bad += 1
398
+ if verbose and bad:
399
+ print(f"[featurize] {bad} SMILES failed to parse", file=sys.stderr)
400
+ return graphs
401
+
402
+
403
+ # ---------------------------------------------------------------------------
404
+ # Training / evaluation
405
+ # ---------------------------------------------------------------------------
406
+
407
+ def iterate_minibatches(
408
+ graphs: List[MolGraph],
409
+ labels: np.ndarray,
410
+ batch_size: int,
411
+ shuffle: bool = True,
412
+ rng: Optional[np.random.Generator] = None,
413
+ ):
414
+ n = len(graphs)
415
+ idx = np.arange(n)
416
+ if shuffle:
417
+ (rng if rng is not None else np.random).shuffle(idx)
418
+ for start in range(0, n, batch_size):
419
+ sel = idx[start:start + batch_size]
420
+ b_graphs = [graphs[i] for i in sel]
421
+ b_labels = labels[sel]
422
+ yield sel, b_graphs, b_labels
423
+
424
+
425
+ def macro_auc(logits: torch.Tensor, labels: torch.Tensor) -> float:
426
+ """Macro-averaged one-vs-rest ROC-AUC, skipping labels with only one class."""
427
+ probs = torch.sigmoid(logits).cpu().numpy()
428
+ y = labels.cpu().numpy()
429
+ aucs: List[float] = []
430
+ for j in range(y.shape[1]):
431
+ if y[:, j].sum() == 0 or y[:, j].sum() == y.shape[0]:
432
+ continue # label has single class in this split
433
+ try:
434
+ aucs.append(roc_auc_score(y[:, j], probs[:, j]))
435
+ except ValueError:
436
+ continue
437
+ if not aucs:
438
+ return 0.0
439
+ return float(np.mean(aucs))
440
+
441
+
442
+ def evaluate_model(model: MPNNEncoder, batch: dict, device: torch.device) -> Tuple[torch.Tensor, float]:
443
+ model.eval()
444
+ with torch.no_grad():
445
+ logits = model(batch)
446
+ auc = macro_auc(logits, batch["labels"])
447
+ return logits, auc
448
+
449
+
450
+ # ---------------------------------------------------------------------------
451
+ # Embedding writer
452
+ # ---------------------------------------------------------------------------
453
+
454
+ def write_embeddings(
455
+ model: MPNNEncoder,
456
+ graphs: List[Optional[MolGraph]],
457
+ ids: List,
458
+ smiles_list: List[str],
459
+ batch_size: int,
460
+ embed_dim: int,
461
+ device: torch.device,
462
+ out_path: str,
463
+ ) -> np.ndarray:
464
+ """Compute and write per-molecule 256-d embeddings to a .npy + companion JSON.
465
+
466
+ Writes <out_path>.npy with shape [n_valid, embed_dim] and <out_path>.json
467
+ with {"ids": [...], "smiles": [...], "indices": [original-row indices]}.
468
+ Skips molecules whose graph is None (failed to featurize).
469
+ """
470
+ model.eval()
471
+ valid_idx = [i for i, g in enumerate(graphs) if g is not None]
472
+ valid_graphs = [graphs[i] for i in valid_idx]
473
+ out = np.zeros((len(valid_graphs), embed_dim), dtype=np.float32)
474
+ with torch.no_grad():
475
+ for start in range(0, len(valid_graphs), batch_size):
476
+ sel = slice(start, start + batch_size)
477
+ batch = collate_batch(valid_graphs[sel])
478
+ batch = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in batch.items()}
479
+ emb = model.penultimate_features(batch)
480
+ out[start:start + batch["n_graphs"]] = emb.cpu().numpy()
481
+ np.save(out_path + ".npy", out)
482
+ index = {
483
+ "ids": [ids[i] for i in valid_idx],
484
+ "smiles": [smiles_list[i] for i in valid_idx],
485
+ "indices": valid_idx,
486
+ }
487
+ with open(out_path + ".json", "w") as f:
488
+ json.dump(index, f)
489
+ print(f"[embed] Wrote {out.shape[0]} embeddings of shape {out.shape[1]} to {out_path}.npy (+ .json index)")
490
+ return out
491
+
492
+
493
+ # ---------------------------------------------------------------------------
494
+ # Checkpoint writer
495
+ # ---------------------------------------------------------------------------
496
+
497
+ def save_checkpoint(model: MPNNEncoder, path: str, config: dict) -> None:
498
+ torch.save({"state_dict": model.state_dict(), "config": config}, path)
499
+ print(f"[checkpoint] Saved model to {path}")
500
+
501
+
502
+ def load_checkpoint(model: MPNNEncoder, path: str, device: torch.device) -> dict:
503
+ ckpt = torch.load(path, map_location=device, weights_only=False)
504
+ model.load_state_dict(ckpt["state_dict"])
505
+ return ckpt.get("config", {})
506
+
507
+
508
+ # ---------------------------------------------------------------------------
509
+ # SMILES-only embedding mode (--embed-smiles-csv)
510
+ # ---------------------------------------------------------------------------
511
+
512
+ def load_smiles_csv(path: str) -> List[str]:
513
+ """Load a CSV of SMILES (column: nonStereoSMILES or smiles)."""
514
+ with open(path, newline="") as f:
515
+ reader = csv.reader(f)
516
+ header = next(reader)
517
+ # Determine SMILES column
518
+ col = None
519
+ for cand in ("nonStereoSMILES", "SMILES", "smiles"):
520
+ if cand in header:
521
+ col = header.index(cand)
522
+ break
523
+ if col is None:
524
+ col = 0 # fall back to first column
525
+ rows = list(reader)
526
+ return [r[col].strip() for r in rows]
527
+
528
+
529
+ # ---------------------------------------------------------------------------
530
+ # Main
531
+ # ---------------------------------------------------------------------------
532
+
533
+ def build_model(device: torch.device) -> MPNNEncoder:
534
+ model = MPNNEncoder(
535
+ atom_dim=ATOM_FEATURE_DIM,
536
+ bond_dim=BOND_FEATURE_DIM,
537
+ hidden_dim=128,
538
+ n_steps=3,
539
+ embed_dim=256,
540
+ n_tasks=138,
541
+ dropout=0.1,
542
+ )
543
+ model = model.to(device)
544
+ return model
545
+
546
+
547
+ def main(argv: Optional[List[str]] = None) -> int:
548
+ parser = argparse.ArgumentParser(description="PINO disjoint MPNN odor encoder (pure PyTorch)")
549
+ parser.add_argument("--csv", default="artifacts/disjoint_encoder/openpom_curated_disjoint.csv",
550
+ help="Input OpenPOM-style CSV (default disjoint corpus).")
551
+ parser.add_argument("--epochs", type=int, default=60)
552
+ parser.add_argument("--batch-size", type=int, default=64)
553
+ parser.add_argument("--lr", type=float, default=1e-3)
554
+ parser.add_argument("--seed", type=int, default=2026)
555
+ parser.add_argument("--embed-out", dest="embed_out", default=None,
556
+ help="Write per-molecule 256-d embeddings as .npy + index JSON.")
557
+ parser.add_argument("--checkpoint-out", dest="checkpoint_out", default=None,
558
+ help="Save trained model state_dict + config as .pt.")
559
+ parser.add_argument("--smoke", action="store_true",
560
+ help="Run 3 epochs on 64 molecules on CPU and exit 0.")
561
+ parser.add_argument("--embed-smiles-csv", dest="embed_smiles_csv", default=None,
562
+ help="CSV of SMILES to embed with a loaded checkpoint instead of training.")
563
+ parser.add_argument("--load-checkpoint", dest="load_checkpoint", default=None,
564
+ help="Path to a saved .pt checkpoint (required with --embed-smiles-csv).")
565
+ args = parser.parse_args(argv)
566
+
567
+ # --- device / determinism ---
568
+ set_seed(args.seed)
569
+ device = torch.device("cpu") if (args.smoke or not torch.cuda.is_available()) else torch.device("cuda")
570
+ print(f"[config] device={device} seed={args.seed} epochs={args.epochs} batch_size={args.batch_size} lr={args.lr}")
571
+
572
+ # --- smoke mode overrides ---
573
+ smoke = bool(args.smoke)
574
+ if smoke:
575
+ args.epochs = 3
576
+
577
+ # --- SMILES-only embedding mode (no training) ---
578
+ if args.embed_smiles_csv is not None:
579
+ if args.load_checkpoint is None:
580
+ print("[error] --embed-smiles-csv requires --load-checkpoint", file=sys.stderr)
581
+ return 2
582
+ model = build_model(device)
583
+ cfg = load_checkpoint(model, args.load_checkpoint, device)
584
+ print(f"[embed-smiles] Loaded checkpoint config: {cfg}")
585
+ smiles = load_smiles_csv(args.embed_smiles_csv)
586
+ print(f"[embed-smiles] Loaded {len(smiles)} SMILES from {args.embed_smiles_csv}")
587
+ graphs = featurize_all(smiles, verbose=True)
588
+ n_ok = sum(1 for g in graphs if g is not None)
589
+ print(f"[embed-smiles] Featurized {n_ok}/{len(smiles)} molecules OK")
590
+ ids = list(range(len(smiles)))
591
+ out_path = args.embed_out or "embeddings_smiles"
592
+ write_embeddings(model, graphs, ids, smiles, args.batch_size, 256, device, out_path)
593
+ return 0
594
+
595
+ # --- load training data ---
596
+ csv_path = args.csv
597
+ if not os.path.exists(csv_path):
598
+ print(f"[error] CSV not found: {csv_path}", file=sys.stderr)
599
+ return 1
600
+ smiles_list, labels, label_names = load_csv(csv_path)
601
+ print(f"[data] Loaded {len(smiles_list)} molecules, {len(label_names)} labels from {csv_path}")
602
+
603
+ if smoke:
604
+ smiles_list = smiles_list[:64]
605
+ labels = labels[:64]
606
+ print(f"[smoke] Truncated to {len(smiles_list)} molecules, {args.epochs} epochs.")
607
+
608
+ # --- featurize ---
609
+ graphs = featurize_all(smiles_list, verbose=True)
610
+ valid_mask = np.array([g is not None for g in graphs])
611
+ n_bad = int((~valid_mask).sum())
612
+ if n_bad > 0:
613
+ print(f"[data] Dropping {n_bad} molecules that failed featurization", file=sys.stderr)
614
+ graphs = [g for g in graphs if g is not None]
615
+ smiles_list = [s for s, m in zip(smiles_list, valid_mask) if m]
616
+ labels = labels[valid_mask]
617
+
618
+ n_mols = len(graphs)
619
+ print(f"[data] {n_mols} valid molecules after featurization")
620
+
621
+ # --- train/val split (seeded 90/10) ---
622
+ rng = np.random.default_rng(args.seed)
623
+ perm = rng.permutation(n_mols)
624
+ n_val = max(1, n_mols // 10)
625
+ val_idx = perm[:n_val]
626
+ train_idx = perm[n_val:]
627
+ train_graphs = [graphs[i] for i in train_idx]
628
+ train_labels = labels[train_idx]
629
+ val_graphs = [graphs[i] for i in val_idx]
630
+ val_labels = labels[val_idx]
631
+ print(f"[split] train={len(train_idx)} val={len(val_idx)}")
632
+
633
+ # --- build model ---
634
+ model = build_model(device)
635
+ n_params = sum(p.numel() for p in model.parameters())
636
+ print(f"[model] MPNNEncoder parameters: {n_params:,}")
637
+
638
+ # --- optimizer / loss ---
639
+ optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)
640
+ criterion = nn.BCEWithLogitsLoss()
641
+
642
+ # --- training loop ---
643
+ shuffle_rng = np.random.default_rng(args.seed)
644
+ for epoch in range(1, args.epochs + 1):
645
+ model.train()
646
+ epoch_loss = 0.0
647
+ n_batches = 0
648
+ for _, bg, bl in iterate_minibatches(train_graphs, train_labels, args.batch_size,
649
+ shuffle=True, rng=shuffle_rng):
650
+ batch = collate_batch(bg, bl)
651
+ batch = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in batch.items()}
652
+ optimizer.zero_grad()
653
+ logits = model(batch)
654
+ loss = criterion(logits, batch["labels"])
655
+ loss.backward()
656
+ optimizer.step()
657
+ epoch_loss += float(loss.item())
658
+ n_batches += 1
659
+ train_loss = epoch_loss / max(n_batches, 1)
660
+
661
+ # Macro-AUC on validation split
662
+ val_batch = collate_batch(val_graphs, val_labels)
663
+ val_batch = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in val_batch.items()}
664
+ _, val_auc = evaluate_model(model, val_batch, device)
665
+ print(f"[epoch {epoch:3d}/{args.epochs}] train_loss={train_loss:.4f} val_macro_auc={val_auc:.4f}")
666
+
667
+ # --- write embeddings for ALL rows of input CSV ---
668
+ if args.embed_out:
669
+ # Use ids = row index in the (smoke-truncated) input CSV.
670
+ ids = list(range(n_mols))
671
+ emb = write_embeddings(model, graphs, ids, smiles_list, args.batch_size,
672
+ model.embed_dim, device, args.embed_out)
673
+ print(f"[embed] shape={emb.shape}")
674
+
675
+ # --- checkpoint ---
676
+ if args.checkpoint_out:
677
+ save_checkpoint(
678
+ model,
679
+ args.checkpoint_out,
680
+ {
681
+ "atom_dim": ATOM_FEATURE_DIM,
682
+ "bond_dim": BOND_FEATURE_DIM,
683
+ "hidden_dim": 128,
684
+ "n_steps": 3,
685
+ "embed_dim": 256,
686
+ "n_tasks": 138,
687
+ "label_names": label_names,
688
+ "epochs": args.epochs,
689
+ "seed": args.seed,
690
+ },
691
+ )
692
+
693
+ if smoke:
694
+ print("[smoke] OK — smoke test passed.")
695
+
696
+ return 0
697
+
698
+
699
+ if __name__ == "__main__":
700
+ raise SystemExit(main())