manpreet88 commited on
Commit
44f889e
·
1 Parent(s): 58616ba

Create CL.py

Browse files
Files changed (1) hide show
  1. PolyFusion/CL.py +1803 -0
PolyFusion/CL.py ADDED
@@ -0,0 +1,1803 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import csv
4
+ import json
5
+ import time
6
+ import math
7
+ import random
8
+ import shutil
9
+ from pathlib import Path
10
+ from typing import List, Optional, Tuple, Dict
11
+
12
+ # Increase csv field size limit safely
13
+ try:
14
+ csv.field_size_limit(sys.maxsize)
15
+ except OverflowError:
16
+ csv.field_size_limit(2**31 - 1)
17
+
18
+ import numpy as np
19
+ import pandas as pd
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+ from torch.utils.data import Dataset, DataLoader
24
+
25
+ # PyG building blocks
26
+ try:
27
+ from torch_geometric.nn import GINEConv
28
+ from torch_geometric.nn.models import SchNet as PyGSchNet
29
+ from torch_geometric.nn import radius_graph
30
+ except Exception as e:
31
+ # we keep imports guarded — if these fail, user will get a clear error later
32
+ GINEConv = None
33
+ PyGSchNet = None
34
+ radius_graph = None
35
+
36
+ # HF Trainer & Transformers
37
+ from transformers import TrainingArguments, Trainer, DebertaV2ForMaskedLM, DebertaV2Tokenizer
38
+ from transformers import DataCollatorForLanguageModeling
39
+ from transformers.trainer_callback import TrainerCallback
40
+
41
+ from sklearn.model_selection import train_test_split
42
+ from sklearn.metrics import accuracy_score, f1_score, mean_squared_error, mean_absolute_error
43
+
44
+ # ---------------------------
45
+ # Config / Hyperparams (kept same as in your scripts)
46
+ # ---------------------------
47
+ P_MASK = 0.15
48
+ MAX_ATOMIC_Z = 85
49
+ MASK_ATOM_ID = MAX_ATOMIC_Z + 1
50
+
51
+ # GINE params
52
+ NODE_EMB_DIM = 300
53
+ EDGE_EMB_DIM = 300
54
+ NUM_GNN_LAYERS = 5
55
+
56
+ # SchNet params (from your file)
57
+ SCHNET_NUM_GAUSSIANS = 50
58
+ SCHNET_NUM_INTERACTIONS = 6
59
+ SCHNET_CUTOFF = 10.0
60
+ SCHNET_MAX_NEIGHBORS = 64
61
+ SCHNET_HIDDEN = 600
62
+
63
+ # Fingerprint (MLM) params
64
+ FP_LENGTH = 2048
65
+ MASK_TOKEN_ID_FP = 2 # consistent with your fingerprint file
66
+ VOCAB_SIZE_FP = 3
67
+
68
+ # PSMILES/Deberta params (from your file)
69
+ DEBERTA_HIDDEN = 600
70
+ PSMILES_MAX_LEN = 128
71
+
72
+ # Contrastive params
73
+ TEMPERATURE = 0.07
74
+
75
+ # Reconstruction loss weight (balance between contrastive and reconstruction objectives)
76
+ REC_LOSS_WEIGHT = 1.0 # you can tune this (e.g., 0.5, 1.0)
77
+
78
+ # Training args (same across files)
79
+ OUTPUT_DIR = "./multimodal_output"
80
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
81
+ BEST_GINE_DIR = "./gin_output/best"
82
+ BEST_SCHNET_DIR = "./schnet_output/best"
83
+ BEST_FP_DIR = "./fingerprint_mlm_output/best"
84
+ BEST_PSMILES_DIR = "./polybert_output/best"
85
+
86
+ training_args = TrainingArguments(
87
+ output_dir=OUTPUT_DIR,
88
+ overwrite_output_dir=True,
89
+ num_train_epochs=25,
90
+ per_device_train_batch_size=16,
91
+ per_device_eval_batch_size=8,
92
+ gradient_accumulation_steps=4,
93
+ eval_strategy="epoch",
94
+ logging_steps=100,
95
+ learning_rate=1e-4,
96
+ weight_decay=0.01,
97
+ eval_accumulation_steps=1000,
98
+ fp16=torch.cuda.is_available(),
99
+ save_strategy="epoch",
100
+ save_steps=500,
101
+ disable_tqdm=False,
102
+ logging_first_step=True,
103
+ report_to=[],
104
+ dataloader_num_workers=0,
105
+ load_best_model_at_end=True,
106
+ metric_for_best_model="eval_loss",
107
+ greater_is_better=False,
108
+ )
109
+
110
+ # ======== robust device selection =========
111
+ USE_CUDA = torch.cuda.is_available()
112
+ if USE_CUDA:
113
+ device = torch.device("cuda") # respects CUDA_VISIBLE_DEVICES
114
+ else:
115
+ device = torch.device("cpu")
116
+ print("Device:", device)
117
+
118
+ # ======== deterministic seeds =========
119
+ SEED = 42
120
+ random.seed(SEED)
121
+ np.random.seed(SEED)
122
+ torch.manual_seed(SEED)
123
+ if USE_CUDA:
124
+ torch.cuda.manual_seed_all(SEED)
125
+
126
+ # ---------------------------
127
+ # Utility / small helpers
128
+ # ---------------------------
129
+
130
+ def safe_get(d: dict, key: str, default=None):
131
+ return d[key] if (isinstance(d, dict) and key in d) else default
132
+
133
+
134
+ def match_edge_attr_to_index(edge_index: torch.Tensor, edge_attr: torch.Tensor, target_dim: int = 3):
135
+ # determine device to allocate zero tensors on
136
+ dev = None
137
+ if edge_attr is not None and hasattr(edge_attr, "device"):
138
+ dev = edge_attr.device
139
+ elif edge_index is not None and hasattr(edge_index, "device"):
140
+ dev = edge_index.device
141
+ else:
142
+ dev = torch.device("cpu")
143
+
144
+ if edge_index is None or edge_index.numel() == 0:
145
+ return torch.zeros((0, target_dim), dtype=torch.float, device=dev)
146
+ E_idx = edge_index.size(1)
147
+ if edge_attr is None or edge_attr.numel() == 0:
148
+ return torch.zeros((E_idx, target_dim), dtype=torch.float, device=dev)
149
+ E_attr = edge_attr.size(0)
150
+ if E_attr == E_idx:
151
+ if edge_attr.size(1) != target_dim:
152
+ D = edge_attr.size(1)
153
+ if D < target_dim:
154
+ pad = torch.zeros((E_attr, target_dim - D), dtype=torch.float, device=edge_attr.device)
155
+ return torch.cat([edge_attr, pad], dim=1)
156
+ else:
157
+ return edge_attr[:, :target_dim]
158
+ return edge_attr
159
+ if E_attr * 2 == E_idx:
160
+ try:
161
+ return torch.cat([edge_attr, edge_attr], dim=0)
162
+ except Exception:
163
+ pass
164
+ reps = (E_idx + E_attr - 1) // E_attr
165
+ edge_rep = edge_attr.repeat(reps, 1)[:E_idx]
166
+ if edge_rep.size(1) != target_dim:
167
+ D = edge_rep.size(1)
168
+ if D < target_dim:
169
+ pad = torch.zeros((E_idx, target_dim - D), dtype=torch.float, device=edge_rep.device)
170
+ edge_rep = torch.cat([edge_rep, pad], dim=1)
171
+ else:
172
+ edge_rep = edge_rep[:, :target_dim]
173
+ return edge_rep
174
+
175
+ # Optimized BFS to compute distances to visible anchors (used if needed)
176
+ def bfs_distances_to_visible(edge_index: torch.Tensor, num_nodes: int, masked_idx: np.ndarray, visible_idx: np.ndarray, k_anchors: int):
177
+ INF = num_nodes + 1
178
+ selected_dists = np.zeros((num_nodes, k_anchors), dtype=np.float32)
179
+ selected_mask = np.zeros((num_nodes, k_anchors), dtype=np.bool_)
180
+ if edge_index is None or edge_index.numel() == 0:
181
+ return selected_dists, selected_mask
182
+ src = edge_index[0].tolist()
183
+ dst = edge_index[1].tolist()
184
+ adj = [[] for _ in range(num_nodes)]
185
+ for u, v in zip(src, dst):
186
+ if 0 <= u < num_nodes and 0 <= v < num_nodes:
187
+ adj[u].append(v)
188
+ visible_set = set(visible_idx.tolist()) if isinstance(visible_idx, (np.ndarray, list)) else set(visible_idx.cpu().tolist())
189
+ for a in np.atleast_1d(masked_idx).tolist():
190
+ if a < 0 or a >= num_nodes:
191
+ continue
192
+ q = [a]
193
+ visited = [-1] * num_nodes
194
+ visited[a] = 0
195
+ head = 0
196
+ found = []
197
+ while head < len(q) and len(found) < k_anchors:
198
+ u = q[head]; head += 1
199
+ for v in adj[u]:
200
+ if visited[v] == -1:
201
+ visited[v] = visited[u] + 1
202
+ q.append(v)
203
+ if v in visible_set:
204
+ found.append((visited[v], v))
205
+ if len(found) >= k_anchors:
206
+ break
207
+ if len(found) > 0:
208
+ found.sort(key=lambda x: x[0])
209
+ k = min(k_anchors, len(found))
210
+ for i in range(k):
211
+ selected_dists[a, i] = float(found[i][0])
212
+ selected_mask[a, i] = True
213
+ return selected_dists, selected_mask
214
+
215
+ # ---------------------------
216
+ # Data loading / preprocessing (streaming to disk to avoid memory spike)
217
+ # ---------------------------
218
+ CSV_PATH = "Polymer_Foundational_Model/polymer_structures_unified_processed.csv"
219
+ TARGET_ROWS = 2000000
220
+ CHUNKSIZE = 50000
221
+
222
+ PREPROC_DIR = "preprocessed_samples"
223
+ os.makedirs(PREPROC_DIR, exist_ok=True)
224
+
225
+ # The per-sample file format: torch.save(sample_dict, sample_path)
226
+ # sample_dict keys: 'gine', 'schnet', 'fp', 'psmiles_raw'
227
+ # 'gine' -> dict with: node_atomic (list/int tensor), chirality (list/float tensor), formal_charge (list/float tensor), edge_index (2xE list), edge_attr (E x 3 list)
228
+ # 'schnet' -> dict with: atomic (list), coords (list of [x,y,z])
229
+ # 'fp' -> list of length FP_LENGTH (0/1 ints)
230
+ # 'psmiles_raw' -> raw psmiles string
231
+
232
+ def prepare_or_load_data_streaming():
233
+ # If PREPROC_DIR already contains per-sample files, reuse them
234
+ existing = sorted([p for p in Path(PREPROC_DIR).glob("sample_*.pt")])
235
+ if len(existing) > 0:
236
+ print(f"Found {len(existing)} preprocessed sample files in {PREPROC_DIR}; reusing those (no reparse).")
237
+ return [str(p) for p in existing]
238
+
239
+ print("No existing per-sample preprocessed folder found. Parsing CSV chunked and writing per-sample files (streaming).")
240
+ rows_read = 0
241
+ sample_idx = 0
242
+
243
+ # We'll parse CSV in chunks and for each row, if it contains all modalities, write sample to disk
244
+ for chunk in pd.read_csv(CSV_PATH, engine="python", chunksize=CHUNKSIZE):
245
+ # Pre-extract columns presence
246
+ has_graph = "graph" in chunk.columns
247
+ has_geometry = "geometry" in chunk.columns
248
+ has_fp = "fingerprints" in chunk.columns
249
+ has_psmiles = "psmiles" in chunk.columns
250
+
251
+ for i_row in range(len(chunk)):
252
+ if rows_read >= TARGET_ROWS:
253
+ break
254
+ row = chunk.iloc[i_row]
255
+
256
+ # Prepare placeholders
257
+ gine_sample = None
258
+ schnet_sample = None
259
+ fp_sample = None
260
+ psmiles_raw = None
261
+
262
+ # Parse graph
263
+ if has_graph:
264
+ val = row.get("graph", "")
265
+ try:
266
+ graph_field = json.loads(val) if isinstance(val, str) and val.strip() != "" else (val if not isinstance(val, str) else None)
267
+ except Exception:
268
+ graph_field = None
269
+ if graph_field:
270
+ node_features = safe_get(graph_field, "node_features", None)
271
+ if node_features:
272
+ atomic_nums = []
273
+ chirality_vals = []
274
+ formal_charges = []
275
+ for nf in node_features:
276
+ an = safe_get(nf, "atomic_num", None)
277
+ if an is None:
278
+ an = safe_get(nf, "atomic_number", 0)
279
+ ch = safe_get(nf, "chirality", 0)
280
+ fc = safe_get(nf, "formal_charge", 0)
281
+ try:
282
+ atomic_nums.append(int(an))
283
+ except Exception:
284
+ atomic_nums.append(0)
285
+ chirality_vals.append(float(ch))
286
+ formal_charges.append(float(fc))
287
+ n_nodes = len(atomic_nums)
288
+ edge_indices_raw = safe_get(graph_field, "edge_indices", None)
289
+ edge_features_raw = safe_get(graph_field, "edge_features", None)
290
+ edge_index = None
291
+ edge_attr = None
292
+ if edge_indices_raw is None:
293
+ adj_mat = safe_get(graph_field, "adjacency_matrix", None)
294
+ if adj_mat:
295
+ srcs = []
296
+ dsts = []
297
+ for i_r, row_adj in enumerate(adj_mat):
298
+ for j, val2 in enumerate(row_adj):
299
+ if val2:
300
+ srcs.append(i_r); dsts.append(j)
301
+ if len(srcs) > 0:
302
+ edge_index = [srcs, dsts]
303
+ E = len(srcs)
304
+ edge_attr = [[0.0, 0.0, 0.0] for _ in range(E)]
305
+ else:
306
+ srcs, dsts = [], []
307
+ # handle multiple formats
308
+ if isinstance(edge_indices_raw, list) and len(edge_indices_raw) > 0 and isinstance(edge_indices_raw[0], list):
309
+ # either list of pairs or two lists
310
+ first = edge_indices_raw[0]
311
+ if len(first) == 2 and isinstance(first[0], int):
312
+ # maybe list of pairs
313
+ try:
314
+ srcs = [int(p[0]) for p in edge_indices_raw]
315
+ dsts = [int(p[1]) for p in edge_indices_raw]
316
+ except Exception:
317
+ srcs, dsts = [], []
318
+ else:
319
+ # maybe [[srcs],[dsts]]
320
+ try:
321
+ srcs = [int(x) for x in edge_indices_raw[0]]
322
+ dsts = [int(x) for x in edge_indices_raw[1]]
323
+ except Exception:
324
+ srcs, dsts = [], []
325
+ if len(srcs) == 0 and isinstance(edge_indices_raw, list) and all(isinstance(p, (list, tuple)) and len(p) == 2 for p in edge_indices_raw):
326
+ srcs = [int(p[0]) for p in edge_indices_raw]
327
+ dsts = [int(p[1]) for p in edge_indices_raw]
328
+ if len(srcs) > 0:
329
+ edge_index = [srcs, dsts]
330
+ if edge_features_raw and isinstance(edge_features_raw, list):
331
+ bond_types = []
332
+ stereos = []
333
+ is_conjs = []
334
+ for ef in edge_features_raw:
335
+ bt = safe_get(ef, "bond_type", 0)
336
+ st = safe_get(ef, "stereo", 0)
337
+ ic = safe_get(ef, "is_conjugated", False)
338
+ bond_types.append(float(bt)); stereos.append(float(st)); is_conjs.append(float(1.0 if ic else 0.0))
339
+ edge_attr = list(zip(bond_types, stereos, is_conjs))
340
+ else:
341
+ E = len(srcs)
342
+ edge_attr = [[0.0, 0.0, 0.0] for _ in range(E)]
343
+
344
+ if edge_index is not None:
345
+ gine_sample = {
346
+ "node_atomic": atomic_nums,
347
+ "node_chirality": chirality_vals,
348
+ "node_charge": formal_charges,
349
+ "edge_index": edge_index,
350
+ "edge_attr": edge_attr,
351
+ }
352
+
353
+ # Parse geometry for SchNet
354
+ if has_geometry and schnet_sample is None:
355
+ val = row.get("geometry", "")
356
+ try:
357
+ geom = json.loads(val) if isinstance(val, str) and val.strip() != "" else (val if not isinstance(val, str) else None)
358
+ conf = geom.get("best_conformer") if isinstance(geom, dict) else None
359
+ if conf:
360
+ atomic = conf.get("atomic_numbers", [])
361
+ coords = conf.get("coordinates", [])
362
+ if len(atomic) == len(coords) and len(atomic) > 0:
363
+ schnet_sample = {"atomic": atomic, "coords": coords}
364
+ except Exception:
365
+ schnet_sample = None
366
+
367
+ # Parse fingerprints
368
+ if has_fp:
369
+ fpval = row.get("fingerprints", "")
370
+ if fpval is None or (isinstance(fpval, str) and fpval.strip() == ""):
371
+ fp_sample = [0] * FP_LENGTH
372
+ else:
373
+ try:
374
+ fp_json = json.loads(fpval) if isinstance(fpval, str) else fpval
375
+ except Exception:
376
+ try:
377
+ fp_json = json.loads(str(fpval).replace("'", '"'))
378
+ except Exception:
379
+ parts = [p.strip().strip('"').strip("'") for p in str(fpval).split(",")]
380
+ bits = [1 if p in ("1", "True", "true") else 0 for p in parts[:FP_LENGTH]]
381
+ if len(bits) < FP_LENGTH:
382
+ bits += [0] * (FP_LENGTH - len(bits))
383
+ fp_sample = bits
384
+ if fp_sample is None:
385
+ bits = safe_get(fp_json, "morgan_r3_bits", None) if isinstance(fp_json, dict) else (fp_json if isinstance(fp_json, list) else None)
386
+ if bits is None:
387
+ fp_sample = [0] * FP_LENGTH
388
+ else:
389
+ normalized = []
390
+ for b in bits:
391
+ if isinstance(b, str):
392
+ b_clean = b.strip().strip('"').strip("'")
393
+ normalized.append(1 if b_clean in ("1", "True", "true") else 0)
394
+ elif isinstance(b, (int, np.integer)):
395
+ normalized.append(1 if int(b) != 0 else 0)
396
+ else:
397
+ normalized.append(0)
398
+ if len(normalized) >= FP_LENGTH:
399
+ break
400
+ if len(normalized) < FP_LENGTH:
401
+ normalized.extend([0] * (FP_LENGTH - len(normalized)))
402
+ fp_sample = normalized[:FP_LENGTH]
403
+
404
+ # Parse psmiles
405
+ if has_psmiles:
406
+ s = row.get("psmiles", "")
407
+ if s is None:
408
+ psmiles_raw = ""
409
+ else:
410
+ psmiles_raw = str(s)
411
+
412
+ # If we have at least two modalities (prefer all four), write the sample
413
+ # For safety, we require psmiles and fp at minimum OR graph+psmiles etc.
414
+ modalities_present = sum([1 if x is not None else 0 for x in [gine_sample, schnet_sample, fp_sample, psmiles_raw]])
415
+ if modalities_present >= 2:
416
+ sample = {
417
+ "gine": gine_sample,
418
+ "schnet": schnet_sample,
419
+ "fp": fp_sample,
420
+ "psmiles_raw": psmiles_raw
421
+ }
422
+ sample_path = os.path.join(PREPROC_DIR, f"sample_{sample_idx:08d}.pt")
423
+ try:
424
+ torch.save(sample, sample_path)
425
+ except Exception as save_e:
426
+ print("Warning: failed to torch.save sample:", save_e)
427
+ # fallback to json write small dict (safe)
428
+ try:
429
+ with open(sample_path + ".json", "w") as fjson:
430
+ json.dump(sample, fjson)
431
+ # indicate via filename with .json
432
+ sample_path = sample_path + ".json"
433
+ except Exception:
434
+ pass
435
+
436
+ sample_idx += 1
437
+ rows_read += 1
438
+
439
+ # continue to next row
440
+ if rows_read >= TARGET_ROWS:
441
+ break
442
+
443
+ print(f"Wrote {sample_idx} sample files to {PREPROC_DIR}.")
444
+ return [str(p) for p in sorted(Path(PREPROC_DIR).glob("sample_*.pt"))]
445
+
446
+ sample_files = prepare_or_load_data_streaming()
447
+
448
+ # ---------------------------
449
+ # Prepare tokenizer for psmiles (deferred, but we still attempt HF tokenizer; fallback created)
450
+ # ---------------------------
451
+ try:
452
+ SPM_MODEL = "spm.model"
453
+ if Path(SPM_MODEL).exists():
454
+ tokenizer = DebertaV2Tokenizer(vocab_file=SPM_MODEL, do_lower_case=False)
455
+ tokenizer.add_special_tokens({"pad_token": "<pad>", "mask_token": "<mask>"})
456
+ tokenizer.pad_token = "<pad>"
457
+ tokenizer.mask_token = "<mask>"
458
+ else:
459
+ tokenizer = DebertaV2Tokenizer.from_pretrained("microsoft/deberta-v2-xlarge", use_fast=False)
460
+ tokenizer.add_special_tokens({"pad_token": "<pad>", "mask_token": "<mask>"})
461
+ tokenizer.pad_token = "<pad>"
462
+ tokenizer.mask_token = "<mask>"
463
+ except Exception as e:
464
+ print("Warning: Deberta tokenizer creation failed:", e)
465
+ # create a simple fallback tokenizer (char-level)
466
+ class SimplePSMILESTokenizer:
467
+ def __init__(self, max_len=PSMILES_MAX_LEN):
468
+ chars = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=#()[]@+/\\.")
469
+ self.vocab = {c: i + 5 for i, c in enumerate(chars)}
470
+ self.vocab["<pad>"] = 0
471
+ self.vocab["<mask>"] = 1
472
+ self.vocab["<unk>"] = 2
473
+ self.vocab["<cls>"] = 3
474
+ self.vocab["<sep>"] = 4
475
+ self.mask_token = "<mask>"
476
+ self.mask_token_id = self.vocab[self.mask_token]
477
+ self.vocab_size = len(self.vocab)
478
+ self.max_len = max_len
479
+
480
+ def __call__(self, s, truncation=True, padding="max_length", max_length=None):
481
+ max_len = max_length or self.max_len
482
+ toks = [self.vocab.get(ch, self.vocab["<unk>"]) for ch in list(s)][:max_len]
483
+ attn = [1] * len(toks)
484
+ if len(toks) < max_len:
485
+ pad = [self.vocab["<pad>"]] * (max_len - len(toks))
486
+ toks = toks + pad
487
+ attn = attn + [0] * (max_len - len(attn))
488
+ return {"input_ids": toks, "attention_mask": attn}
489
+
490
+ tokenizer = SimplePSMILESTokenizer()
491
+
492
+ # ---------------------------
493
+ # Lazy dataset: loads per-sample file on demand and tokenizes psmiles on-the-fly
494
+ # ---------------------------
495
+ class LazyMultimodalDataset(Dataset):
496
+ def __init__(self, sample_file_list: List[str], tokenizer, fp_length=FP_LENGTH, psmiles_max_len=PSMILES_MAX_LEN):
497
+ self.files = sample_file_list
498
+ self.tokenizer = tokenizer
499
+ self.fp_length = fp_length
500
+ self.psmiles_max_len = psmiles_max_len
501
+
502
+ def __len__(self):
503
+ return len(self.files)
504
+
505
+ def __getitem__(self, idx):
506
+ sample_path = self.files[idx]
507
+ # prefer torch.load if .pt, else try json
508
+ if sample_path.endswith(".pt"):
509
+ sample = torch.load(sample_path, map_location="cpu")
510
+ else:
511
+ # fallback json load
512
+ with open(sample_path, "r") as f:
513
+ sample = json.load(f)
514
+
515
+ # GINE: convert lists to tensors (still on CPU)
516
+ gine_raw = sample.get("gine", None)
517
+ gine_item = None
518
+ if gine_raw:
519
+ node_atomic = torch.tensor(gine_raw.get("node_atomic", []), dtype=torch.long)
520
+ node_chirality = torch.tensor(gine_raw.get("node_chirality", []), dtype=torch.float)
521
+ node_charge = torch.tensor(gine_raw.get("node_charge", []), dtype=torch.float)
522
+ if gine_raw.get("edge_index", None) is not None:
523
+ ei = gine_raw["edge_index"]
524
+ edge_index = torch.tensor(ei, dtype=torch.long)
525
+ else:
526
+ edge_index = torch.tensor([[], []], dtype=torch.long)
527
+ ea_raw = gine_raw.get("edge_attr", None)
528
+ if ea_raw:
529
+ edge_attr = torch.tensor(ea_raw, dtype=torch.float)
530
+ else:
531
+ edge_attr = torch.zeros((edge_index.size(1), 3), dtype=torch.float)
532
+ gine_item = {"z": node_atomic, "chirality": node_chirality, "formal_charge": node_charge, "edge_index": edge_index, "edge_attr": edge_attr}
533
+ else:
534
+ gine_item = {"z": torch.tensor([], dtype=torch.long), "chirality": torch.tensor([], dtype=torch.float), "formal_charge": torch.tensor([], dtype=torch.float), "edge_index": torch.tensor([[], []], dtype=torch.long), "edge_attr": torch.zeros((0, 3), dtype=torch.float)}
535
+
536
+ # SchNet
537
+ schnet_raw = sample.get("schnet", None)
538
+ if schnet_raw:
539
+ s_z = torch.tensor(schnet_raw.get("atomic", []), dtype=torch.long)
540
+ s_pos = torch.tensor(schnet_raw.get("coords", []), dtype=torch.float)
541
+ schnet_item = {"z": s_z, "pos": s_pos}
542
+ else:
543
+ schnet_item = {"z": torch.tensor([], dtype=torch.long), "pos": torch.tensor([], dtype=torch.float)}
544
+
545
+ # Fingerprint — stored as list of ints; convert to tensor here
546
+ fp_raw = sample.get("fp", None)
547
+ if fp_raw is None:
548
+ fp_vec = torch.zeros((self.fp_length,), dtype=torch.long)
549
+ else:
550
+ # if fp_raw is already tensor-like, handle it
551
+ if isinstance(fp_raw, (list, tuple)):
552
+ arr = list(fp_raw)[:self.fp_length]
553
+ if len(arr) < self.fp_length:
554
+ arr = arr + [0] * (self.fp_length - len(arr))
555
+ fp_vec = torch.tensor(arr, dtype=torch.long)
556
+ elif isinstance(fp_raw, torch.Tensor):
557
+ fp_vec = fp_raw.clone().to(torch.long)
558
+ else:
559
+ # fallback
560
+ fp_vec = torch.zeros((self.fp_length,), dtype=torch.long)
561
+
562
+ # PSMILES: raw string, tokenize now
563
+ psm_raw = sample.get("psmiles_raw", "")
564
+ if psm_raw is None:
565
+ psm_raw = ""
566
+ enc = self.tokenizer(psm_raw, truncation=True, padding="max_length", max_length=self.psmiles_max_len)
567
+ p_input_ids = torch.tensor(enc["input_ids"], dtype=torch.long)
568
+ p_attn = torch.tensor(enc["attention_mask"], dtype=torch.bool)
569
+
570
+ return {
571
+ "gine": {"z": gine_item["z"], "chirality": gine_item["chirality"], "formal_charge": gine_item["formal_charge"], "edge_index": gine_item["edge_index"], "edge_attr": gine_item["edge_attr"], "num_nodes": int(gine_item["z"].size(0)) if gine_item["z"].numel() > 0 else 0},
572
+ "schnet": {"z": schnet_item["z"], "pos": schnet_item["pos"]},
573
+ "fp": {"input_ids": fp_vec},
574
+ "psmiles": {"input_ids": p_input_ids, "attention_mask": p_attn}
575
+ }
576
+
577
+ # instantiate dataset lazily
578
+ dataset = LazyMultimodalDataset(sample_files, tokenizer, fp_length=FP_LENGTH, psmiles_max_len=PSMILES_MAX_LEN)
579
+
580
+ # train/val split
581
+ train_idx, val_idx = train_test_split(list(range(len(dataset))), test_size=0.2, random_state=42)
582
+ train_subset = torch.utils.data.Subset(dataset, train_idx)
583
+ val_subset = torch.utils.data.Subset(dataset, val_idx)
584
+
585
+ # For manual evaluation (used by evaluate_multimodal), create a DataLoader with num_workers=0
586
+ def multimodal_collate(batch_list):
587
+ """
588
+ Given a list of items as returned by MultimodalDataset.__getitem__, build a batched mini-batch
589
+ that the encoders accept.
590
+ """
591
+ B = len(batch_list)
592
+ # GINE batching
593
+ all_z = []
594
+ all_ch = []
595
+ all_fc = []
596
+ all_edge_index = []
597
+ all_edge_attr = []
598
+ batch_mapping = []
599
+ node_offset = 0
600
+ for i, item in enumerate(batch_list):
601
+ g = item["gine"]
602
+ z = g["z"]
603
+ n = z.size(0)
604
+ all_z.append(z)
605
+ all_ch.append(g["chirality"])
606
+ all_fc.append(g["formal_charge"])
607
+ batch_mapping.append(torch.full((n,), i, dtype=torch.long))
608
+ if g["edge_index"] is not None and g["edge_index"].numel() > 0:
609
+ ei_offset = g["edge_index"] + node_offset
610
+ all_edge_index.append(ei_offset)
611
+ ea = match_edge_attr_to_index(g["edge_index"], g["edge_attr"], target_dim=3)
612
+ all_edge_attr.append(ea)
613
+ node_offset += n
614
+ if len(all_z) == 0:
615
+ # create zero-length placeholders for empty batch
616
+ z_batch = torch.tensor([], dtype=torch.long)
617
+ ch_batch = torch.tensor([], dtype=torch.float)
618
+ fc_batch = torch.tensor([], dtype=torch.float)
619
+ batch_batch = torch.tensor([], dtype=torch.long)
620
+ edge_index_batched = torch.empty((2,0), dtype=torch.long)
621
+ edge_attr_batched = torch.zeros((0,3), dtype=torch.float)
622
+ else:
623
+ z_batch = torch.cat(all_z, dim=0)
624
+ ch_batch = torch.cat(all_ch, dim=0)
625
+ fc_batch = torch.cat(all_fc, dim=0)
626
+ batch_batch = torch.cat(batch_mapping, dim=0)
627
+ if len(all_edge_index) > 0:
628
+ edge_index_batched = torch.cat(all_edge_index, dim=1)
629
+ edge_attr_batched = torch.cat(all_edge_attr, dim=0)
630
+ else:
631
+ edge_index_batched = torch.empty((2,0), dtype=torch.long)
632
+ edge_attr_batched = torch.zeros((0,3), dtype=torch.float)
633
+
634
+ # SchNet batching: concat nodes and create batch indices
635
+ all_sz = []
636
+ all_pos = []
637
+ schnet_batch = []
638
+ for i, item in enumerate(batch_list):
639
+ s = item["schnet"]
640
+ s_z = s["z"]
641
+ s_pos = s["pos"]
642
+ if s_z.numel() == 0:
643
+ continue
644
+ all_sz.append(s_z)
645
+ all_pos.append(s_pos)
646
+ schnet_batch.append(torch.full((s_z.size(0),), i, dtype=torch.long))
647
+ if len(all_sz) == 0:
648
+ s_z_batch = torch.tensor([], dtype=torch.long)
649
+ s_pos_batch = torch.tensor([], dtype=torch.float)
650
+ s_batch_batch = torch.tensor([], dtype=torch.long)
651
+ else:
652
+ s_z_batch = torch.cat(all_sz, dim=0)
653
+ s_pos_batch = torch.cat(all_pos, dim=0)
654
+ s_batch_batch = torch.cat(schnet_batch, dim=0)
655
+
656
+ # FP batching: each fp is vector [L] (long 0/1). We make attention_mask all ones.
657
+ fp_ids = torch.stack([item["fp"]["input_ids"] if isinstance(item["fp"]["input_ids"], torch.Tensor) else torch.tensor(item["fp"]["input_ids"], dtype=torch.long) for item in batch_list], dim=0)
658
+ fp_attn = torch.ones_like(fp_ids, dtype=torch.bool)
659
+
660
+ # PSMILES
661
+ p_ids = torch.stack([item["psmiles"]["input_ids"] for item in batch_list], dim=0)
662
+ p_attn = torch.stack([item["psmiles"]["attention_mask"] for item in batch_list], dim=0)
663
+
664
+ return {
665
+ "gine": {"z": z_batch, "chirality": ch_batch, "formal_charge": fc_batch, "edge_index": edge_index_batched, "edge_attr": edge_attr_batched, "batch": batch_batch},
666
+ "schnet": {"z": s_z_batch, "pos": s_pos_batch, "batch": s_batch_batch},
667
+ "fp": {"input_ids": fp_ids, "attention_mask": fp_attn},
668
+ "psmiles": {"input_ids": p_ids, "attention_mask": p_attn}
669
+ }
670
+
671
+ train_loader = DataLoader(train_subset, batch_size=training_args.per_device_train_batch_size, shuffle=True, collate_fn=multimodal_collate, num_workers=0, drop_last=False)
672
+ val_loader = DataLoader(val_subset, batch_size=training_args.per_device_eval_batch_size, shuffle=False, collate_fn=multimodal_collate, num_workers=0, drop_last=False)
673
+
674
+ # ---------------------------
675
+ # Encoder definitions (kept same as original with minimal device-safe guards)
676
+ # ---------------------------
677
+
678
+ class GineBlock(nn.Module):
679
+ def __init__(self, node_dim):
680
+ super().__init__()
681
+ self.mlp = nn.Sequential(
682
+ nn.Linear(node_dim, node_dim),
683
+ nn.ReLU(),
684
+ nn.Linear(node_dim, node_dim)
685
+ )
686
+ # If GINEConv is not available, we still construct placeholder to fail later with message
687
+ if GINEConv is None:
688
+ raise RuntimeError("GINEConv is not available. Install torch_geometric with compatible versions.")
689
+ self.conv = GINEConv(self.mlp)
690
+ self.bn = nn.BatchNorm1d(node_dim)
691
+ self.act = nn.ReLU()
692
+
693
+ def forward(self, x, edge_index, edge_attr):
694
+ x = self.conv(x, edge_index, edge_attr)
695
+ x = self.bn(x)
696
+ x = self.act(x)
697
+ return x
698
+
699
+ class GineEncoder(nn.Module):
700
+ def __init__(self, node_emb_dim=NODE_EMB_DIM, edge_emb_dim=EDGE_EMB_DIM, num_layers=NUM_GNN_LAYERS, max_atomic_z=MAX_ATOMIC_Z):
701
+ super().__init__()
702
+ self.atom_emb = nn.Embedding(num_embeddings=MASK_ATOM_ID+1, embedding_dim=node_emb_dim, padding_idx=None)
703
+ self.node_attr_proj = nn.Sequential(
704
+ nn.Linear(2, node_emb_dim),
705
+ nn.ReLU(),
706
+ nn.Linear(node_emb_dim, node_emb_dim)
707
+ )
708
+ self.edge_encoder = nn.Sequential(
709
+ nn.Linear(3, edge_emb_dim),
710
+ nn.ReLU(),
711
+ nn.Linear(edge_emb_dim, edge_emb_dim)
712
+ )
713
+ if edge_emb_dim != node_emb_dim:
714
+ self._edge_to_node_proj = nn.Linear(edge_emb_dim, node_emb_dim)
715
+ else:
716
+ self._edge_to_node_proj = None
717
+ self.gnn_layers = nn.ModuleList([GineBlock(node_emb_dim) for _ in range(num_layers)])
718
+ # global pooling projection
719
+ self.pool_proj = nn.Linear(node_emb_dim, node_emb_dim)
720
+
721
+ # node-level classifier head for reconstructing atomic ids if needed
722
+ self.node_classifier = nn.Linear(node_emb_dim, MASK_ATOM_ID+1)
723
+
724
+ def _compute_node_reps(self, z, chirality, formal_charge, edge_index, edge_attr):
725
+ device = next(self.parameters()).device
726
+ atom_embedding = self.atom_emb(z.to(device))
727
+ if chirality is None or formal_charge is None:
728
+ node_attr = torch.zeros((z.size(0), 2), device=device)
729
+ else:
730
+ node_attr = torch.stack([chirality, formal_charge], dim=1).to(atom_embedding.device)
731
+ node_attr_emb = self.node_attr_proj(node_attr)
732
+ x = atom_embedding + node_attr_emb
733
+ if edge_attr is None or edge_attr.numel() == 0:
734
+ edge_emb = torch.zeros((0, EDGE_EMB_DIM), dtype=torch.float, device=x.device)
735
+ else:
736
+ edge_emb = self.edge_encoder(edge_attr.to(x.device))
737
+ if self._edge_to_node_proj is not None and edge_emb.numel() > 0:
738
+ edge_for_conv = self._edge_to_node_proj(edge_emb)
739
+ else:
740
+ edge_for_conv = edge_emb
741
+
742
+ h = x
743
+ for layer in self.gnn_layers:
744
+ h = layer(h, edge_index.to(h.device), edge_for_conv)
745
+ return h
746
+
747
+ def forward(self, z, chirality, formal_charge, edge_index, edge_attr, batch=None):
748
+ h = self._compute_node_reps(z, chirality, formal_charge, edge_index, edge_attr)
749
+ if batch is None:
750
+ pooled = torch.mean(h, dim=0, keepdim=True)
751
+ else:
752
+ bsize = int(batch.max().item() + 1) if batch.numel() > 0 else 1
753
+ pooled = torch.zeros((bsize, h.size(1)), device=h.device)
754
+ for i in range(bsize):
755
+ mask = batch == i
756
+ if mask.sum() == 0:
757
+ continue
758
+ pooled[i] = h[mask].mean(dim=0)
759
+ return self.pool_proj(pooled)
760
+
761
+ def node_logits(self, z, chirality, formal_charge, edge_index, edge_attr):
762
+ h = self._compute_node_reps(z, chirality, formal_charge, edge_index, edge_attr)
763
+ logits = self.node_classifier(h)
764
+ return logits
765
+
766
+ class NodeSchNetWrapper(nn.Module):
767
+ def __init__(self, hidden_channels=SCHNET_HIDDEN, num_interactions=SCHNET_NUM_INTERACTIONS, num_gaussians=SCHNET_NUM_GAUSSIANS, cutoff=SCHNET_CUTOFF, max_num_neighbors=SCHNET_MAX_NEIGHBORS):
768
+ super().__init__()
769
+ if PyGSchNet is None:
770
+ raise RuntimeError("PyG SchNet is not available. Install torch_geometric with compatible extras.")
771
+ self.schnet = PyGSchNet(hidden_channels=hidden_channels, num_filters=hidden_channels, num_interactions=num_interactions, num_gaussians=num_gaussians, cutoff=cutoff, max_num_neighbors=max_num_neighbors)
772
+ self.pool_proj = nn.Linear(hidden_channels, hidden_channels)
773
+ self.cutoff = cutoff
774
+ self.max_num_neighbors = max_num_neighbors
775
+ self.node_classifier = nn.Linear(hidden_channels, MASK_ATOM_ID+1)
776
+
777
+ def forward(self, z, pos, batch=None):
778
+ device = next(self.parameters()).device
779
+ z = z.to(device)
780
+ pos = pos.to(device)
781
+ if batch is None:
782
+ batch = torch.zeros(z.size(0), dtype=torch.long, device=z.device)
783
+ try:
784
+ edge_index = radius_graph(pos, r=self.cutoff, batch=batch, max_num_neighbors=self.max_num_neighbors)
785
+ except Exception:
786
+ edge_index = None
787
+
788
+ node_h = None
789
+ try:
790
+ if hasattr(self.schnet, "embedding"):
791
+ node_h = self.schnet.embedding(z)
792
+ else:
793
+ node_h = self.schnet.embedding(z)
794
+ except Exception:
795
+ node_h = None
796
+
797
+ if node_h is not None and edge_index is not None and edge_index.numel() > 0:
798
+ row, col = edge_index
799
+ edge_weight = (pos[row] - pos[col]).norm(dim=-1)
800
+ edge_attr = None
801
+ if hasattr(self.schnet, "distance_expansion"):
802
+ try:
803
+ edge_attr = self.schnet.distance_expansion(edge_weight)
804
+ except Exception:
805
+ edge_attr = None
806
+ if edge_attr is None and hasattr(self.schnet, "gaussian_smearing"):
807
+ try:
808
+ edge_attr = self.schnet.gaussian_smearing(edge_weight)
809
+ except Exception:
810
+ edge_attr = None
811
+ if hasattr(self.schnet, "interactions") and getattr(self.schnet, "interactions") is not None:
812
+ for interaction in self.schnet.interactions:
813
+ try:
814
+ node_h = node_h + interaction(node_h, edge_index, edge_weight, edge_attr)
815
+ except TypeError:
816
+ node_h = node_h + interaction(node_h, edge_index, edge_weight)
817
+ if node_h is None:
818
+ try:
819
+ out = self.schnet(z=z, pos=pos, batch=batch)
820
+ if isinstance(out, torch.Tensor) and out.dim() == 2 and out.size(0) == z.size(0):
821
+ node_h = out
822
+ elif hasattr(out, "last_hidden_state"):
823
+ node_h = out.last_hidden_state
824
+ elif isinstance(out, (tuple, list)) and len(out) > 0 and isinstance(out[0], torch.Tensor):
825
+ cand = out[0]
826
+ if cand.dim() == 2 and cand.size(0) == z.size(0):
827
+ node_h = cand
828
+ except Exception as e:
829
+ raise RuntimeError("Failed to obtain node-level embeddings from PyG SchNet.") from e
830
+
831
+ bsize = int(batch.max().item()) + 1 if z.numel() > 0 else 1
832
+ pooled = torch.zeros((bsize, node_h.size(1)), device=node_h.device)
833
+ for i in range(bsize):
834
+ mask = batch == i
835
+ if mask.sum() == 0:
836
+ continue
837
+ pooled[i] = node_h[mask].mean(dim=0)
838
+ return self.pool_proj(pooled)
839
+
840
+ def node_logits(self, z, pos, batch=None):
841
+ device = next(self.parameters()).device
842
+ z = z.to(device)
843
+ pos = pos.to(device)
844
+ if batch is None:
845
+ batch = torch.zeros(z.size(0), dtype=torch.long, device=z.device)
846
+ try:
847
+ edge_index = radius_graph(pos, r=self.cutoff, batch=batch, max_num_neighbors=self.max_num_neighbors)
848
+ except Exception:
849
+ edge_index = None
850
+
851
+ node_h = None
852
+ try:
853
+ if hasattr(self.schnet, "embedding"):
854
+ node_h = self.schnet.embedding(z)
855
+ except Exception:
856
+ node_h = None
857
+
858
+ if node_h is not None and edge_index is not None and edge_index.numel() > 0:
859
+ row, col = edge_index
860
+ edge_weight = (pos[row] - pos[col]).norm(dim=-1)
861
+ edge_attr = None
862
+ if hasattr(self.schnet, "distance_expansion"):
863
+ try:
864
+ edge_attr = self.schnet.distance_expansion(edge_weight)
865
+ except Exception:
866
+ edge_attr = None
867
+ if edge_attr is None and hasattr(self.schnet, "gaussian_smearing"):
868
+ try:
869
+ edge_attr = self.schnet.gaussian_smearing(edge_weight)
870
+ except Exception:
871
+ edge_attr = None
872
+ if hasattr(self.schnet, "interactions") and getattr(self.schnet, "interactions") is not None:
873
+ for interaction in self.schnet.interactions:
874
+ try:
875
+ node_h = node_h + interaction(node_h, edge_index, edge_weight, edge_attr)
876
+ except TypeError:
877
+ node_h = node_h + interaction(node_h, edge_index, edge_weight)
878
+
879
+ if node_h is None:
880
+ out = self.schnet(z=z, pos=pos, batch=batch)
881
+ if isinstance(out, torch.Tensor):
882
+ node_h = out
883
+ elif hasattr(out, "last_hidden_state"):
884
+ node_h = out.last_hidden_state
885
+ elif isinstance(out, (tuple, list)) and len(out) > 0 and isinstance(out[0], torch.Tensor):
886
+ node_h = out[0]
887
+ else:
888
+ raise RuntimeError("Unable to obtain node embeddings for SchNet node_logits")
889
+
890
+ logits = self.node_classifier(node_h)
891
+ return logits
892
+
893
+ class FingerprintEncoder(nn.Module):
894
+ def __init__(self, vocab_size=VOCAB_SIZE_FP, hidden_dim=256, seq_len=FP_LENGTH, num_layers=4, nhead=8, dim_feedforward=1024, dropout=0.1):
895
+ super().__init__()
896
+ self.token_emb = nn.Embedding(vocab_size, hidden_dim)
897
+ self.pos_emb = nn.Embedding(seq_len, hidden_dim)
898
+ encoder_layer = nn.TransformerEncoderLayer(d_model=hidden_dim, nhead=nhead, dim_feedforward=dim_feedforward, dropout=dropout, batch_first=True)
899
+ self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
900
+ self.pool_proj = nn.Linear(hidden_dim, hidden_dim)
901
+ self.seq_len = seq_len
902
+ self.token_proj = nn.Linear(hidden_dim, vocab_size)
903
+
904
+ def forward(self, input_ids, attention_mask=None):
905
+ device = next(self.parameters()).device
906
+ input_ids = input_ids.to(device)
907
+ B, L = input_ids.shape
908
+ x = self.token_emb(input_ids)
909
+ pos_ids = torch.arange(L, device=input_ids.device).unsqueeze(0).expand(B, -1)
910
+ x = x + self.pos_emb(pos_ids)
911
+ if attention_mask is not None:
912
+ key_padding_mask = ~attention_mask.to(input_ids.device)
913
+ else:
914
+ key_padding_mask = None
915
+ out = self.transformer(x, src_key_padding_mask=key_padding_mask)
916
+ if attention_mask is None:
917
+ pooled = out.mean(dim=1)
918
+ else:
919
+ am = attention_mask.to(out.device).float().unsqueeze(-1)
920
+ pooled = (out * am).sum(dim=1) / (am.sum(dim=1).clamp(min=1.0))
921
+ return self.pool_proj(pooled)
922
+
923
+ def token_logits(self, input_ids, attention_mask=None):
924
+ device = next(self.parameters()).device
925
+ input_ids = input_ids.to(device)
926
+ B, L = input_ids.shape
927
+ x = self.token_emb(input_ids)
928
+ pos_ids = torch.arange(L, device=input_ids.device).unsqueeze(0).expand(B, -1)
929
+ x = x + self.pos_emb(pos_ids)
930
+ if attention_mask is not None:
931
+ key_padding_mask = ~attention_mask.to(input_ids.device)
932
+ else:
933
+ key_padding_mask = None
934
+ out = self.transformer(x, src_key_padding_mask=key_padding_mask)
935
+ logits = self.token_proj(out)
936
+ return logits
937
+
938
+ class PSMILESDebertaEncoder(nn.Module):
939
+ def __init__(self, model_dir_or_name: Optional[str] = None):
940
+ super().__init__()
941
+ try:
942
+ if model_dir_or_name is not None and os.path.isdir(model_dir_or_name):
943
+ self.model = DebertaV2ForMaskedLM.from_pretrained(model_dir_or_name)
944
+ else:
945
+ self.model = DebertaV2ForMaskedLM.from_pretrained("microsoft/deberta-v2-xlarge")
946
+ except Exception as e:
947
+ print("Warning: couldn't load DebertaV2 pretrained weights; initializing randomly.", e)
948
+ from transformers import DebertaV2Config
949
+ cfg = DebertaV2Config(vocab_size=getattr(tokenizer, "vocab_size", 300), hidden_size=DEBERTA_HIDDEN, num_attention_heads=12, num_hidden_layers=12, intermediate_size=512)
950
+ self.model = DebertaV2ForMaskedLM(cfg)
951
+ self.pool_proj = nn.Linear(self.model.config.hidden_size, self.model.config.hidden_size)
952
+
953
+ def forward(self, input_ids, attention_mask=None):
954
+ device = next(self.parameters()).device
955
+ input_ids = input_ids.to(device)
956
+ if attention_mask is not None:
957
+ attention_mask = attention_mask.to(device)
958
+ outputs = self.model.base_model(input_ids=input_ids, attention_mask=attention_mask, return_dict=True)
959
+ last_hidden = outputs.last_hidden_state
960
+ if attention_mask is None:
961
+ pooled = last_hidden.mean(dim=1)
962
+ else:
963
+ am = attention_mask.unsqueeze(-1).to(last_hidden.device).float()
964
+ pooled = (last_hidden * am).sum(dim=1) / (am.sum(dim=1).clamp(min=1.0))
965
+ return self.pool_proj(pooled)
966
+
967
+ def token_logits(self, input_ids, attention_mask=None, labels=None):
968
+ device = next(self.parameters()).device
969
+ input_ids = input_ids.to(device)
970
+ if attention_mask is not None:
971
+ attention_mask = attention_mask.to(device)
972
+ if labels is not None:
973
+ labels = labels.to(device)
974
+ outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, labels=labels, return_dict=True)
975
+ return outputs.loss
976
+ else:
977
+ outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, return_dict=True)
978
+ return outputs.logits
979
+
980
+ # ---------------------------
981
+ # Multimodal wrapper & loss (kept same)
982
+ # ---------------------------
983
+ class MultimodalContrastiveModel(nn.Module):
984
+ def __init__(self,
985
+ gine_encoder: Optional[GineEncoder],
986
+ schnet_encoder: Optional[NodeSchNetWrapper],
987
+ fp_encoder: Optional[FingerprintEncoder],
988
+ psmiles_encoder: Optional[PSMILESDebertaEncoder],
989
+ emb_dim: int = 600):
990
+ super().__init__()
991
+ self.gine = gine_encoder
992
+ self.schnet = schnet_encoder
993
+ self.fp = fp_encoder
994
+ self.psmiles = psmiles_encoder
995
+ self.proj_gine = nn.Linear(getattr(self.gine, "pool_proj").out_features if self.gine is not None else emb_dim, emb_dim) if self.gine is not None else None
996
+ self.proj_schnet = nn.Linear(getattr(self.schnet, "pool_proj").out_features if self.schnet is not None else emb_dim, emb_dim) if self.schnet is not None else None
997
+ self.proj_fp = nn.Linear(getattr(self.fp, "pool_proj").out_features if self.fp is not None else emb_dim, emb_dim) if self.fp is not None else None
998
+ self.proj_psmiles = nn.Linear(getattr(self.psmiles, "pool_proj").out_features if self.psmiles is not None else emb_dim, emb_dim) if self.psmiles is not None else None
999
+ self.temperature = TEMPERATURE
1000
+ self.ce_loss = nn.CrossEntropyLoss(ignore_index=-100, reduction='mean')
1001
+
1002
+ def encode(self, batch_mods: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
1003
+ device = next(self.parameters()).device
1004
+ embs = {}
1005
+ B = None
1006
+ if 'gine' in batch_mods and self.gine is not None:
1007
+ g = batch_mods['gine']
1008
+ emb_g = self.gine(g['z'], g['chirality'], g['formal_charge'], g['edge_index'], g['edge_attr'], g.get('batch', None))
1009
+ embs['gine'] = F.normalize(self.proj_gine(emb_g), dim=-1)
1010
+ B = embs['gine'].size(0) if B is None else B
1011
+ if 'schnet' in batch_mods and self.schnet is not None:
1012
+ s = batch_mods['schnet']
1013
+ emb_s = self.schnet(s['z'], s['pos'], s.get('batch', None))
1014
+ embs['schnet'] = F.normalize(self.proj_schnet(emb_s), dim=-1)
1015
+ B = embs['schnet'].size(0) if B is None else B
1016
+ if 'fp' in batch_mods and self.fp is not None:
1017
+ f = batch_mods['fp']
1018
+ emb_f = self.fp(f['input_ids'], f.get('attention_mask', None))
1019
+ embs['fp'] = F.normalize(self.proj_fp(emb_f), dim=-1)
1020
+ B = embs['fp'].size(0) if B is None else B
1021
+ if 'psmiles' in batch_mods and self.psmiles is not None:
1022
+ p = batch_mods['psmiles']
1023
+ emb_p = self.psmiles(p['input_ids'], p.get('attention_mask', None))
1024
+ embs['psmiles'] = F.normalize(self.proj_psmiles(emb_p), dim=-1)
1025
+ B = embs['psmiles'].size(0) if B is None else B
1026
+ return embs
1027
+
1028
+ def forward(self, batch_mods: Dict[str, torch.Tensor], mask_target: str):
1029
+ device = next(self.parameters()).device
1030
+ embs = self.encode(batch_mods)
1031
+ info = {}
1032
+ if mask_target not in embs:
1033
+ return torch.tensor(0.0, device=device), {"batch_size": 0}
1034
+ target = embs[mask_target]
1035
+ other_keys = [k for k in embs.keys() if k != mask_target]
1036
+ if len(other_keys) == 0:
1037
+ return torch.tensor(0.0, device=device), {"batch_size": target.size(0)}
1038
+ anchor = torch.stack([embs[k] for k in other_keys], dim=0).mean(dim=0)
1039
+ logits = torch.matmul(anchor, target.T) / self.temperature
1040
+ B = logits.size(0)
1041
+ labels = torch.arange(B, device=logits.device)
1042
+ info_nce_loss = F.cross_entropy(logits, labels)
1043
+ info['info_nce_loss'] = float(info_nce_loss.detach().cpu().item())
1044
+
1045
+ rec_losses = []
1046
+ rec_details = {}
1047
+
1048
+ try:
1049
+ if 'gine' in batch_mods and self.gine is not None:
1050
+ gm = batch_mods['gine']
1051
+ labels_nodes = gm.get('labels', None)
1052
+ if labels_nodes is not None:
1053
+ node_logits = self.gine.node_logits(gm['z'], gm['chirality'], gm['formal_charge'], gm['edge_index'], gm['edge_attr'])
1054
+ if labels_nodes.dim() == 1 and node_logits.size(0) == labels_nodes.size(0):
1055
+ loss_gine = self.ce_loss(node_logits, labels_nodes.to(node_logits.device))
1056
+ rec_losses.append(loss_gine)
1057
+ rec_details['gine_rec_loss'] = float(loss_gine.detach().cpu().item())
1058
+ except Exception as e:
1059
+ print("Warning: GINE reconstruction loss computation failed:", e)
1060
+
1061
+ try:
1062
+ if 'schnet' in batch_mods and self.schnet is not None:
1063
+ sm = batch_mods['schnet']
1064
+ labels_nodes = sm.get('labels', None)
1065
+ if labels_nodes is not None:
1066
+ node_logits = self.schnet.node_logits(sm['z'], sm['pos'], sm.get('batch', None))
1067
+ if labels_nodes.dim() == 1 and node_logits.size(0) == labels_nodes.size(0):
1068
+ loss_schnet = self.ce_loss(node_logits, labels_nodes.to(node_logits.device))
1069
+ rec_losses.append(loss_schnet)
1070
+ rec_details['schnet_rec_loss'] = float(loss_schnet.detach().cpu().item())
1071
+ except Exception as e:
1072
+ print("Warning: SchNet reconstruction loss computation failed:", e)
1073
+
1074
+ try:
1075
+ if 'fp' in batch_mods and self.fp is not None:
1076
+ fm = batch_mods['fp']
1077
+ labels_fp = fm.get('labels', None)
1078
+ if labels_fp is not None:
1079
+ token_logits = self.fp.token_logits(fm['input_ids'], fm.get('attention_mask', None))
1080
+ Bf, Lf, V = token_logits.shape
1081
+ logits2 = token_logits.view(-1, V)
1082
+ labels2 = labels_fp.view(-1).to(logits2.device)
1083
+ loss_fp = self.ce_loss(logits2, labels2)
1084
+ rec_losses.append(loss_fp)
1085
+ rec_details['fp_rec_loss'] = float(loss_fp.detach().cpu().item())
1086
+ except Exception as e:
1087
+ print("Warning: FP reconstruction loss computation failed:", e)
1088
+
1089
+ try:
1090
+ if 'psmiles' in batch_mods and self.psmiles is not None:
1091
+ pm = batch_mods['psmiles']
1092
+ labels_ps = pm.get('labels', None)
1093
+ if labels_ps is not None and tokenizer is not None:
1094
+ loss_ps = self.psmiles.token_logits(pm['input_ids'], pm.get('attention_mask', None), labels=labels_ps)
1095
+ if isinstance(loss_ps, torch.Tensor):
1096
+ rec_losses.append(loss_ps)
1097
+ rec_details['psmiles_mlm_loss'] = float(loss_ps.detach().cpu().item())
1098
+ except Exception as e:
1099
+ print("Warning: PSMILES MLM loss computation failed:", e)
1100
+
1101
+ if len(rec_losses) > 0:
1102
+ rec_loss_total = sum(rec_losses) / len(rec_losses)
1103
+ info['reconstruction_loss'] = float(rec_loss_total.detach().cpu().item())
1104
+ total_loss = info_nce_loss + REC_LOSS_WEIGHT * rec_loss_total
1105
+ info['total_loss'] = float(total_loss.detach().cpu().item())
1106
+ info.update(rec_details)
1107
+ else:
1108
+ total_loss = info_nce_loss
1109
+ info['reconstruction_loss'] = 0.0
1110
+ info['total_loss'] = float(total_loss.detach().cpu().item())
1111
+
1112
+ return total_loss, info
1113
+
1114
+ # ---------------------------
1115
+ # Instantiate encoders (load weights if available) and move to device with .to(device)
1116
+ gine_encoder = GineEncoder(node_emb_dim=NODE_EMB_DIM, edge_emb_dim=EDGE_EMB_DIM, num_layers=NUM_GNN_LAYERS, max_atomic_z=MAX_ATOMIC_Z)
1117
+ if os.path.exists(os.path.join(BEST_GINE_DIR, "pytorch_model.bin")):
1118
+ try:
1119
+ gine_encoder.load_state_dict(torch.load(os.path.join(BEST_GINE_DIR, "pytorch_model.bin"), map_location="cpu"), strict=False)
1120
+ print("Loaded GINE best weights from", BEST_GINE_DIR)
1121
+ except Exception as e:
1122
+ print("Could not load GINE best weights:", e)
1123
+ gine_encoder.to(device)
1124
+
1125
+ schnet_encoder = NodeSchNetWrapper(hidden_channels=SCHNET_HIDDEN, num_interactions=SCHNET_NUM_INTERACTIONS, num_gaussians=SCHNET_NUM_GAUSSIANS, cutoff=SCHNET_CUTOFF, max_num_neighbors=SCHNET_MAX_NEIGHBORS)
1126
+ if os.path.exists(os.path.join(BEST_SCHNET_DIR, "pytorch_model.bin")):
1127
+ try:
1128
+ schnet_encoder.load_state_dict(torch.load(os.path.join(BEST_SCHNET_DIR, "pytorch_model.bin"), map_location="cpu"), strict=False)
1129
+ print("Loaded SchNet best weights from", BEST_SCHNET_DIR)
1130
+ except Exception as e:
1131
+ print("Could not load SchNet best weights:", e)
1132
+ schnet_encoder.to(device)
1133
+
1134
+ fp_encoder = FingerprintEncoder(vocab_size=VOCAB_SIZE_FP, hidden_dim=256, seq_len=FP_LENGTH, num_layers=4, nhead=8, dim_feedforward=1024, dropout=0.1)
1135
+ if os.path.exists(os.path.join(BEST_FP_DIR, "pytorch_model.bin")):
1136
+ try:
1137
+ fp_encoder.load_state_dict(torch.load(os.path.join(BEST_FP_DIR, "pytorch_model.bin"), map_location="cpu"), strict=False)
1138
+ print("Loaded fingerprint encoder best weights from", BEST_FP_DIR)
1139
+ except Exception as e:
1140
+ print("Could not load fingerprint best weights:", e)
1141
+ fp_encoder.to(device)
1142
+
1143
+ psmiles_encoder = None
1144
+ if os.path.isdir(BEST_PSMILES_DIR):
1145
+ try:
1146
+ psmiles_encoder = PSMILESDebertaEncoder(model_dir_or_name=BEST_PSMILES_DIR)
1147
+ print("Loaded Deberta (PSMILES) from", BEST_PSMILES_DIR)
1148
+ except Exception as e:
1149
+ print("Failed to load Deberta from saved directory:", e)
1150
+ if psmiles_encoder is None:
1151
+ try:
1152
+ psmiles_encoder = PSMILESDebertaEncoder(model_dir_or_name=None)
1153
+ except Exception as e:
1154
+ print("Failed to instantiate Deberta encoder:", e)
1155
+ psmiles_encoder.to(device)
1156
+
1157
+ multimodal_model = MultimodalContrastiveModel(gine_encoder, schnet_encoder, fp_encoder, psmiles_encoder, emb_dim=600)
1158
+ multimodal_model.to(device)
1159
+
1160
+ # ---------------------------
1161
+ # Helper to sample masked variant for modalities: (kept same, device-safe)
1162
+ def mask_batch_for_modality(batch: dict, modality: str, p_mask: float = P_MASK):
1163
+ b = {}
1164
+ # GINE:
1165
+ if 'gine' in batch:
1166
+ z = batch['gine']['z'].clone()
1167
+ chir = batch['gine']['chirality'].clone()
1168
+ fc = batch['gine']['formal_charge'].clone()
1169
+ edge_index = batch['gine']['edge_index']
1170
+ edge_attr = batch['gine']['edge_attr']
1171
+ batch_map = batch['gine'].get('batch', None)
1172
+ n_nodes = z.size(0)
1173
+ dev = z.device
1174
+ is_selected = torch.rand(n_nodes, device=dev) < p_mask
1175
+ if is_selected.numel() > 0 and is_selected.all():
1176
+ is_selected[torch.randint(0, n_nodes, (1,), device=dev)] = False
1177
+ labels_z = torch.full_like(z, fill_value=-100)
1178
+ if is_selected.any():
1179
+ sel_idx = torch.nonzero(is_selected).squeeze(-1)
1180
+ if sel_idx.dim() == 0:
1181
+ sel_idx = sel_idx.unsqueeze(0)
1182
+ labels_z[is_selected] = z[is_selected]
1183
+ rand_atomic = torch.randint(1, MAX_ATOMIC_Z+1, (sel_idx.size(0),), dtype=torch.long, device=dev)
1184
+ probs = torch.rand(sel_idx.size(0), device=dev)
1185
+ mask_choice = probs < 0.8
1186
+ rand_choice = (probs >= 0.8) & (probs < 0.9)
1187
+ if mask_choice.any():
1188
+ z[sel_idx[mask_choice]] = MASK_ATOM_ID
1189
+ if rand_choice.any():
1190
+ z[sel_idx[rand_choice]] = rand_atomic[rand_choice]
1191
+ b['gine'] = {"z": z, "chirality": chir, "formal_charge": fc, "edge_index": edge_index, "edge_attr": edge_attr, "batch": batch_map, "labels": labels_z}
1192
+
1193
+ # SchNet:
1194
+ if 'schnet' in batch:
1195
+ z = batch['schnet']['z'].clone()
1196
+ pos = batch['schnet']['pos'].clone()
1197
+ batch_map = batch['schnet'].get('batch', None)
1198
+ n_nodes = z.size(0)
1199
+ dev = z.device
1200
+ is_selected = torch.rand(n_nodes, device=dev) < p_mask
1201
+ if is_selected.numel() > 0 and is_selected.all():
1202
+ is_selected[torch.randint(0, n_nodes, (1,), device=dev)] = False
1203
+ labels_z = torch.full((n_nodes,), -100, dtype=torch.long, device=dev)
1204
+ if is_selected.any():
1205
+ sel_idx = torch.nonzero(is_selected).squeeze(-1)
1206
+ if sel_idx.dim() == 0:
1207
+ sel_idx = sel_idx.unsqueeze(0)
1208
+ labels_z[is_selected] = z[is_selected]
1209
+ probs_c = torch.rand(sel_idx.size(0), device=dev)
1210
+ noisy_choice = probs_c < 0.8
1211
+ randpos_choice = (probs_c >= 0.8) & (probs_c < 0.9)
1212
+ if noisy_choice.any():
1213
+ idx = sel_idx[noisy_choice]
1214
+ noise = torch.randn((idx.size(0), 3), device=pos.device) * 0.5
1215
+ pos[idx] = pos[idx] + noise
1216
+ if randpos_choice.any():
1217
+ idx = sel_idx[randpos_choice]
1218
+ mins = pos.min(dim=0).values
1219
+ maxs = pos.max(dim=0).values
1220
+ randpos = (torch.rand((idx.size(0), 3), device=pos.device) * (maxs - mins)) + mins
1221
+ pos[idx] = randpos
1222
+ b['schnet'] = {"z": z, "pos": pos, "batch": batch_map, "labels": labels_z}
1223
+
1224
+ # FP:
1225
+ if 'fp' in batch:
1226
+ input_ids = batch['fp']['input_ids'].clone()
1227
+ attn = batch['fp'].get('attention_mask', torch.ones_like(input_ids, dtype=torch.bool))
1228
+ B, L = input_ids.shape
1229
+ dev = input_ids.device
1230
+ labels_z = torch.full_like(input_ids, -100)
1231
+ for i in range(B):
1232
+ sel = torch.rand(L, device=dev) < p_mask
1233
+ if sel.numel() > 0 and sel.all():
1234
+ sel[torch.randint(0, L, (1,), device=dev)] = False
1235
+ sel_idx = torch.nonzero(sel).squeeze(-1)
1236
+ if sel_idx.numel() > 0:
1237
+ if sel_idx.dim() == 0:
1238
+ sel_idx = sel_idx.unsqueeze(0)
1239
+ labels_z[i, sel_idx] = input_ids[i, sel_idx]
1240
+ probs = torch.rand(sel_idx.size(0), device=dev)
1241
+ mask_choice = probs < 0.8
1242
+ rand_choice = (probs >= 0.8) & (probs < 0.9)
1243
+ if mask_choice.any():
1244
+ input_ids[i, sel_idx[mask_choice]] = MASK_TOKEN_ID_FP
1245
+ if rand_choice.any():
1246
+ rand_bits = torch.randint(0, 2, (rand_choice.sum().item(),), dtype=torch.long, device=dev)
1247
+ input_ids[i, sel_idx[rand_choice]] = rand_bits
1248
+ b['fp'] = {"input_ids": input_ids, "attention_mask": attn, "labels": labels_z}
1249
+
1250
+ # PSMILES:
1251
+ if 'psmiles' in batch:
1252
+ input_ids = batch['psmiles']['input_ids'].clone()
1253
+ attn = batch['psmiles']['attention_mask'].clone()
1254
+ B, L = input_ids.shape
1255
+ dev = input_ids.device
1256
+ labels_z = torch.full_like(input_ids, -100)
1257
+ if tokenizer is None:
1258
+ b['psmiles'] = {"input_ids": input_ids, "attention_mask": attn, "labels": labels_z}
1259
+ else:
1260
+ mask_token_id = tokenizer.mask_token_id if getattr(tokenizer, "mask_token_id", None) is not None else getattr(tokenizer, "vocab", {}).get("<mask>", 1)
1261
+ for i in range(B):
1262
+ sel = torch.rand(L, device=dev) < p_mask
1263
+ if sel.numel() > 0 and sel.all():
1264
+ sel[torch.randint(0, L, (1,), device=dev)] = False
1265
+ sel_idx = torch.nonzero(sel).squeeze(-1)
1266
+ if sel_idx.numel() > 0:
1267
+ if sel_idx.dim() == 0:
1268
+ sel_idx = sel_idx.unsqueeze(0)
1269
+ labels_z[i, sel_idx] = input_ids[i, sel_idx]
1270
+ probs = torch.rand(sel_idx.size(0), device=dev)
1271
+ mask_choice = probs < 0.8
1272
+ rand_choice = (probs >= 0.8) & (probs < 0.9)
1273
+ if mask_choice.any():
1274
+ input_ids[i, sel_idx[mask_choice]] = mask_token_id
1275
+ if rand_choice.any():
1276
+ rand_ids = torch.randint(0, getattr(tokenizer, "vocab_size", 300), (rand_choice.sum().item(),), dtype=torch.long, device=dev)
1277
+ input_ids[i, sel_idx[rand_choice]] = rand_ids
1278
+ b['psmiles'] = {"input_ids": input_ids, "attention_mask": attn, "labels": labels_z}
1279
+
1280
+ return b
1281
+
1282
+ def mm_batch_to_model_input(masked_batch):
1283
+ mm = {}
1284
+ if 'gine' in masked_batch:
1285
+ gm = masked_batch['gine']
1286
+ mm['gine'] = {"z": gm['z'], "chirality": gm['chirality'], "formal_charge": gm['formal_charge'], "edge_index": gm['edge_index'], "edge_attr": gm['edge_attr'], "batch": gm.get('batch', None), "labels": gm.get('labels', None)}
1287
+ if 'schnet' in masked_batch:
1288
+ sm = masked_batch['schnet']
1289
+ mm['schnet'] = {"z": sm['z'], "pos": sm['pos'], "batch": sm.get('batch', None), "labels": sm.get('labels', None)}
1290
+ if 'fp' in masked_batch:
1291
+ fm = masked_batch['fp']
1292
+ mm['fp'] = {"input_ids": fm['input_ids'], "attention_mask": fm.get('attention_mask', None), "labels": fm.get('labels', None)}
1293
+ if 'psmiles' in masked_batch:
1294
+ pm = masked_batch['psmiles']
1295
+ mm['psmiles'] = {"input_ids": pm['input_ids'], "attention_mask": pm.get('attention_mask', None), "labels": pm.get('labels', None)}
1296
+ return mm
1297
+
1298
+ # ---------------------------
1299
+ # Evaluation function (keeps same semantics)
1300
+ def evaluate_multimodal(model: MultimodalContrastiveModel, val_loader, device, mask_target="fp"):
1301
+ model.eval()
1302
+ total_loss = 0.0
1303
+ total_examples = 0
1304
+ acc_sum = 0.0
1305
+ top5_sum = 0.0
1306
+ mrr_sum = 0.0
1307
+ mean_pos_logit_sum = 0.0
1308
+ mean_neg_logit_sum = 0.0
1309
+ f1_sum = 0.0
1310
+
1311
+ with torch.no_grad():
1312
+ for batch in val_loader:
1313
+ masked_batch = mask_batch_for_modality(batch, mask_target, p_mask=P_MASK)
1314
+ # move to device
1315
+ for k in masked_batch:
1316
+ for subk in masked_batch[k]:
1317
+ if isinstance(masked_batch[k][subk], torch.Tensor):
1318
+ masked_batch[k][subk] = masked_batch[k][subk].to(device)
1319
+ mm_in = mm_batch_to_model_input(masked_batch)
1320
+ embs = model.encode(mm_in)
1321
+ if mask_target not in embs:
1322
+ continue
1323
+ target = embs[mask_target]
1324
+ other_keys = [k for k in embs.keys() if k != mask_target]
1325
+ if len(other_keys) == 0:
1326
+ continue
1327
+ anchor = torch.stack([embs[k] for k in other_keys], dim=0).mean(dim=0)
1328
+ logits = torch.matmul(anchor, target.T) / model.temperature
1329
+ B = logits.size(0)
1330
+ labels = torch.arange(B, device=logits.device)
1331
+ loss = F.cross_entropy(logits, labels)
1332
+ total_loss += loss.item() * B
1333
+ total_examples += B
1334
+
1335
+ preds = logits.argmax(dim=1)
1336
+ acc = (preds == labels).float().mean().item()
1337
+ acc_sum += acc * B
1338
+
1339
+ if B >= 5:
1340
+ topk = min(5, B)
1341
+ topk_indices = torch.topk(logits, k=topk, dim=1).indices
1342
+ hits_topk = (topk_indices == labels.unsqueeze(1)).any(dim=1).float().mean().item()
1343
+ top5_sum += hits_topk * B
1344
+ else:
1345
+ top5_sum += acc * B
1346
+
1347
+ sorted_desc = torch.argsort(logits, dim=1, descending=True)
1348
+ positions = (sorted_desc == labels.unsqueeze(1)).nonzero(as_tuple=False)
1349
+ ranks = torch.zeros(B, device=logits.device).float()
1350
+ if positions.numel() > 0:
1351
+ for p in positions:
1352
+ i, pos = int(p[0].item()), int(p[1].item())
1353
+ ranks[i] = pos + 1.0
1354
+ ranks_nonzero = ranks.clone()
1355
+ ranks_nonzero[ranks_nonzero == 0] = float('inf')
1356
+ mrr = (1.0 / ranks_nonzero).mean().item()
1357
+ mrr_sum += mrr * B
1358
+
1359
+ pos_logits = logits[torch.arange(B), labels]
1360
+ neg_logits = logits.clone()
1361
+ neg_logits[torch.arange(B), labels] = float('-inf')
1362
+ neg_mask = neg_logits != float('-inf')
1363
+ if neg_mask.any():
1364
+ row_counts = neg_mask.sum(dim=1).clamp(min=1).float()
1365
+ sum_neg_per_row = neg_logits.masked_fill(~neg_mask, 0.0).sum(dim=1)
1366
+ mean_neg = (sum_neg_per_row / row_counts).mean().item()
1367
+ else:
1368
+ mean_neg = 0.0
1369
+ mean_pos_logit_sum += pos_logits.mean().item() * B
1370
+ mean_neg_logit_sum += mean_neg * B
1371
+
1372
+ try:
1373
+ labels_np = labels.cpu().numpy()
1374
+ preds_np = preds.cpu().numpy()
1375
+ if len(np.unique(labels_np)) < 2:
1376
+ batch_f1 = float(acc)
1377
+ else:
1378
+ batch_f1 = f1_score(labels_np, preds_np, average='weighted')
1379
+ except Exception:
1380
+ batch_f1 = float(acc)
1381
+ f1_sum += batch_f1 * B
1382
+
1383
+ if total_examples == 0:
1384
+ return {"eval_loss": float("nan"), "eval_accuracy": 0.0, "eval_f1_weighted": 0.0}
1385
+
1386
+ avg_loss = total_loss / total_examples
1387
+ accuracy = acc_sum / total_examples
1388
+ f1_weighted = f1_sum / total_examples
1389
+
1390
+ return {"eval_loss": avg_loss, "eval_accuracy": accuracy, "eval_f1_weighted": f1_weighted}
1391
+
1392
+ # ---------------------------
1393
+ # HF wrapper / Trainer integration (kept same as your part 2, uses lazy loaders)
1394
+ class HFMultimodalModule(nn.Module):
1395
+ def __init__(self, mm_model: MultimodalContrastiveModel):
1396
+ super().__init__()
1397
+ self.mm = mm_model
1398
+
1399
+ def forward(self, **kwargs):
1400
+ if "batch" in kwargs:
1401
+ batch = kwargs["batch"]
1402
+ mask_target = kwargs.get("mask_target", "fp")
1403
+ else:
1404
+ modality_keys = ["gine", "schnet", "fp", "psmiles"]
1405
+ found = {k: v for k, v in kwargs.items() if k in modality_keys}
1406
+ if len(found) > 0:
1407
+ batch = {k: found[k] for k in found}
1408
+ mask_target = kwargs.get("mask_target", "fp")
1409
+ else:
1410
+ raise ValueError("HFMultimodalModule.forward could not find 'batch' nor modality keys in inputs. Inputs keys: {}".format(list(kwargs.keys())))
1411
+ masked_batch = mask_batch_for_modality(batch, mask_target, p_mask=P_MASK)
1412
+ device = next(self.parameters()).device
1413
+ for k in masked_batch:
1414
+ for subk in list(masked_batch[k].keys()):
1415
+ val = masked_batch[k][subk]
1416
+ if isinstance(val, torch.Tensor):
1417
+ masked_batch[k][subk] = val.to(device)
1418
+ mm_in = mm_batch_to_model_input(masked_batch)
1419
+ loss, info = self.mm(mm_in, mask_target)
1420
+ logits = None
1421
+ labels = None
1422
+ try:
1423
+ with torch.no_grad():
1424
+ embs = self.mm.encode(mm_in)
1425
+ if mask_target in embs:
1426
+ target = embs[mask_target]
1427
+ other_keys = [k for k in embs.keys() if k != mask_target]
1428
+ if len(other_keys) > 0:
1429
+ anchor = torch.stack([embs[k] for k in other_keys], dim=0).mean(dim=0)
1430
+ logits = torch.matmul(anchor, target.T) / self.mm.temperature
1431
+ B = logits.size(0)
1432
+ labels = torch.arange(B, device=logits.device)
1433
+ except Exception as e:
1434
+ print("Warning: failed to compute logits/labels inside HFMultimodalModule.forward:", e)
1435
+ logits = None
1436
+ labels = None
1437
+ eval_loss = loss.detach() if isinstance(loss, torch.Tensor) else torch.tensor(float(loss), device=device)
1438
+ out = {"loss": loss, "eval_loss": eval_loss}
1439
+ if logits is not None:
1440
+ out["logits"] = logits
1441
+ if labels is not None:
1442
+ out["labels"] = labels
1443
+ out["mm_info"] = info
1444
+ return out
1445
+
1446
+ hf_model = HFMultimodalModule(multimodal_model)
1447
+ hf_model.to(device)
1448
+
1449
+ class ContrastiveDataCollator:
1450
+ def __init__(self, mask_prob=P_MASK, modalities: Optional[List[str]] = None):
1451
+ self.mask_prob = mask_prob
1452
+ self.modalities = modalities if modalities is not None else ["gine", "schnet", "fp", "psmiles"]
1453
+
1454
+ def __call__(self, features):
1455
+ if isinstance(features, dict):
1456
+ collated = features
1457
+ mask_target = random.choice([m for m in self.modalities if m in collated])
1458
+ return {"batch": collated, "mask_target": mask_target}
1459
+ if isinstance(features, (list, tuple)) and len(features) > 0:
1460
+ first = features[0]
1461
+ if isinstance(first, dict) and 'gine' in first:
1462
+ collated = multimodal_collate(list(features))
1463
+ mask_target = random.choice([m for m in self.modalities if m in collated])
1464
+ return {"batch": collated, "mask_target": mask_target}
1465
+ if isinstance(first, dict) and 'batch' in first:
1466
+ collated = first['batch']
1467
+ mask_target = first.get("mask_target", random.choice([m for m in self.modalities if m in collated]))
1468
+ return {"batch": collated, "mask_target": mask_target}
1469
+ print("ContrastiveDataCollator received unexpected 'features' shape/type.")
1470
+ raise ValueError("ContrastiveDataCollator could not collate input. Expected list[dict] with 'gine' key or already-collated dict.")
1471
+
1472
+ data_collator = ContrastiveDataCollator(mask_prob=P_MASK)
1473
+
1474
+ class VerboseTrainingCallback(TrainerCallback):
1475
+ def __init__(self, patience: int = 10):
1476
+ self.start_time = time.time()
1477
+ self.epoch_start_time = time.time()
1478
+ self._last_train_loss = None
1479
+ self.best_val_loss = float("inf")
1480
+ self.best_epoch = 0
1481
+ self.epochs_no_improve = 0
1482
+ self.patience = patience
1483
+ self.trainer_ref = None
1484
+
1485
+ def save_best_model(self, output_dir_suffix: str = "best"):
1486
+ if self.trainer_ref is None:
1487
+ return
1488
+ try:
1489
+ ckpt_dir = os.path.join(OUTPUT_DIR, output_dir_suffix)
1490
+ os.makedirs(ckpt_dir, exist_ok=True)
1491
+ self.trainer_ref._save(ckpt_dir)
1492
+ print(f"Saved best model checkpoint to {ckpt_dir}")
1493
+ except Exception as e:
1494
+ try:
1495
+ self.trainer_ref.save_model(os.path.join(OUTPUT_DIR, output_dir_suffix))
1496
+ print(f"Saved best model (fallback) to {os.path.join(OUTPUT_DIR, output_dir_suffix)}")
1497
+ except Exception as e2:
1498
+ print("Warning: failed to save best model:", e, e2)
1499
+
1500
+ def on_train_begin(self, args, state, control, **kwargs):
1501
+ self.start_time = time.time()
1502
+ print("" + "="*80)
1503
+ print("🚀 STARTING MULTIMODAL CONTRASTIVE LEARNING TRAINING")
1504
+ print("="*80)
1505
+ model = kwargs.get('model')
1506
+ if model is not None:
1507
+ total_params = sum(p.numel() for p in model.parameters())
1508
+ trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
1509
+ non_trainable_params = total_params - trainable_params
1510
+ print(f"📊 MODEL PARAMETERS:")
1511
+ print(f" Total Parameters: {total_params:,}")
1512
+ print(f" Trainable Parameters: {trainable_params:,}")
1513
+ print(f" Non-trainable Parameters: {non_trainable_params:,}")
1514
+ print(f" Training Progress: 0/{args.num_train_epochs} epochs")
1515
+ print("="*80)
1516
+
1517
+ def on_epoch_begin(self, args, state, control, **kwargs):
1518
+ self.epoch_start_time = time.time()
1519
+ current_epoch = state.epoch if state is not None else 0.0
1520
+ print(f"📈 Epoch {current_epoch + 1:.1f}/{args.num_train_epochs} Starting...")
1521
+
1522
+ def on_epoch_end(self, args, state, control, **kwargs):
1523
+ train_loss = None
1524
+ for log in reversed(state.log_history):
1525
+ if isinstance(log, dict) and 'loss' in log and float(log.get('loss', 0)) != 0.0:
1526
+ train_loss = log['loss']
1527
+ break
1528
+ self._last_train_loss = train_loss
1529
+
1530
+ def on_log(self, args, state, control, logs=None, **kwargs):
1531
+ if logs is not None and 'loss' in logs:
1532
+ current_step = state.global_step
1533
+ current_epoch = state.epoch
1534
+ try:
1535
+ steps_per_epoch = max(1, len(train_loader) // args.gradient_accumulation_steps)
1536
+ except Exception:
1537
+ steps_per_epoch = 1
1538
+ if current_step % max(1, steps_per_epoch // 10) == 0:
1539
+ progress = current_epoch + (current_step % steps_per_epoch) / steps_per_epoch
1540
+ print(f" Step {current_step:4d} | Epoch {progress:.1f} | Train Loss: {logs['loss']:.6f}")
1541
+
1542
+ def on_evaluate(self, args, state, control, metrics=None, **kwargs):
1543
+ current_epoch = state.epoch if state is not None else 0.0
1544
+ epoch_time = time.time() - self.epoch_start_time
1545
+ hf_metrics = metrics if metrics is not None else kwargs.get('metrics', None)
1546
+ hf_eval_loss = None
1547
+ hf_train_loss = self._last_train_loss
1548
+ if hf_metrics is not None:
1549
+ hf_eval_loss = hf_metrics.get('eval_loss', hf_metrics.get('loss', None))
1550
+ if hf_train_loss is None:
1551
+ hf_train_loss = hf_metrics.get('train_loss', hf_train_loss)
1552
+ cl_metrics = {}
1553
+ try:
1554
+ model = kwargs.get('model', None)
1555
+ if model is not None:
1556
+ cl_model = model.mm if hasattr(model, "mm") else model
1557
+ cl_metrics = evaluate_multimodal(cl_model, val_loader, device, mask_target="fp")
1558
+ else:
1559
+ cl_metrics = evaluate_multimodal(multimodal_model, val_loader, device, mask_target="fp")
1560
+ except Exception as e:
1561
+ print("Warning: evaluate_multimodal inside callback failed:", e)
1562
+ if hf_eval_loss is None:
1563
+ hf_eval_loss = cl_metrics.get('eval_loss', None)
1564
+ val_acc = cl_metrics.get('eval_accuracy', 'N/A')
1565
+ val_f1 = cl_metrics.get('eval_f1_weighted', 'N/A')
1566
+ print(f"🔍 EPOCH {current_epoch + 1:.1f} RESULTS:")
1567
+ if hf_train_loss is not None:
1568
+ try:
1569
+ print(f" Train Loss (HF reported): {hf_train_loss:.6f}")
1570
+ except Exception:
1571
+ print(f" Train Loss (HF reported): {hf_train_loss}")
1572
+ else:
1573
+ print(f" Train Loss (HF reported): N/A")
1574
+ if hf_eval_loss is not None:
1575
+ try:
1576
+ print(f" Eval Loss (HF reported): {hf_eval_loss:.6f}")
1577
+ except Exception:
1578
+ print(f" Eval Loss (HF reported): {hf_eval_loss}")
1579
+ else:
1580
+ print(f" Eval Loss (HF reported): N/A")
1581
+ if isinstance(val_acc, float):
1582
+ print(f" Eval Acc (CL evaluator): {val_acc:.6f}")
1583
+ else:
1584
+ print(f" Eval Acc (CL evaluator): {val_acc}")
1585
+ if isinstance(val_f1, float):
1586
+ print(f" Eval F1 Weighted (CL evaluator): {val_f1:.6f}")
1587
+ else:
1588
+ print(f" Eval F1 Weighted (CL evaluator): {val_f1}")
1589
+ current_val = hf_eval_loss if hf_eval_loss is not None else float('inf')
1590
+ improved = False
1591
+ if current_val < self.best_val_loss - 1e-6:
1592
+ improved = True
1593
+ self.best_val_loss = current_val
1594
+ self.best_epoch = current_epoch
1595
+ self.epochs_no_improve = 0
1596
+ try:
1597
+ self.save_best_model("best")
1598
+ except Exception as e:
1599
+ print("Warning: saving best model failed:", e)
1600
+ else:
1601
+ self.epochs_no_improve += 1
1602
+ if self.epochs_no_improve >= self.patience:
1603
+ print(f"Early stopping: no improvement in val_loss for {self.patience} epochs.")
1604
+ control.should_training_stop = True
1605
+ print(f" Epoch Training Time: {epoch_time:.2f}s")
1606
+ print(f" Best Val Loss so far: {self.best_val_loss}")
1607
+ print(f" Epochs since improvement: {self.epochs_no_improve}/{self.patience}")
1608
+ print("-" * 50)
1609
+
1610
+ def on_train_end(self, args, state, control, **kwargs):
1611
+ total_time = time.time() - self.start_time
1612
+ print("" + "="*80)
1613
+ print("🏁 TRAINING COMPLETED")
1614
+ print("="*80)
1615
+ print(f" Total Training Time: {total_time:.2f}s")
1616
+ if state is not None:
1617
+ try:
1618
+ print(f" Total Epochs Completed: {state.epoch + 1:.1f}")
1619
+ except Exception:
1620
+ pass
1621
+ print("="*80)
1622
+
1623
+ from transformers import Trainer as HfTrainer
1624
+
1625
+ class CLTrainer(HfTrainer):
1626
+ def evaluate(self, eval_dataset=None, ignore_keys=None, metric_key_prefix="eval"):
1627
+ try:
1628
+ metrics = super().evaluate(eval_dataset=eval_dataset, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix) or {}
1629
+ except Exception as e:
1630
+ print("Warning: super().evaluate() raised an exception. Falling back to CL-only evaluator.")
1631
+ import traceback
1632
+ traceback.print_exc()
1633
+ try:
1634
+ cl_model = self.model.mm if hasattr(self.model, "mm") else self.model
1635
+ cl_metrics = evaluate_multimodal(cl_model, val_loader, device, mask_target="fp")
1636
+ metrics = {k: float(v) if isinstance(v, (float, int, np.floating, np.integer)) else v for k, v in cl_metrics.items()}
1637
+ metrics["epoch"] = float(self.state.epoch) if getattr(self.state, "epoch", None) is not None else metrics.get("epoch", 0.0)
1638
+ except Exception as e2:
1639
+ print("Fallback evaluate_multimodal failed as well:", e2)
1640
+ traceback.print_exc()
1641
+ metrics = {"eval_loss": float("nan"), "epoch": float(self.state.epoch) if getattr(self.state, "epoch", None) is not None else 0.0}
1642
+ return metrics
1643
+ try:
1644
+ cl_model = self.model.mm if hasattr(self.model, "mm") else self.model
1645
+ cl_metrics = evaluate_multimodal(cl_model, val_loader, device, mask_target="fp")
1646
+ except Exception as e:
1647
+ print("Warning: evaluate_multimodal failed inside CLTrainer.evaluate():", e)
1648
+ cl_metrics = {}
1649
+ for k, v in cl_metrics.items():
1650
+ try:
1651
+ metrics[k] = float(v)
1652
+ except Exception:
1653
+ metrics[k] = v
1654
+ if 'eval_loss' not in metrics and 'eval_loss' in cl_metrics:
1655
+ try:
1656
+ metrics['eval_loss'] = float(cl_metrics['eval_loss'])
1657
+ except Exception:
1658
+ metrics['eval_loss'] = cl_metrics['eval_loss']
1659
+ if "epoch" not in metrics:
1660
+ metrics["epoch"] = float(self.state.epoch) if getattr(self.state, "epoch", None) is not None else metrics.get("epoch", 0.0)
1661
+ return metrics
1662
+
1663
+ def _save(self, output_dir: str):
1664
+ os.makedirs(output_dir, exist_ok=True)
1665
+ try:
1666
+ self.state.save_to_json(os.path.join(output_dir, "trainer_state.json"))
1667
+ except Exception:
1668
+ pass
1669
+ try:
1670
+ model_to_save = self.model.mm if hasattr(self.model, "mm") else self.model
1671
+ torch.save(model_to_save.state_dict(), os.path.join(output_dir, "pytorch_model.bin"))
1672
+ except Exception as e:
1673
+ try:
1674
+ if hasattr(self.model, "save_pretrained"):
1675
+ self.model.save_pretrained(output_dir)
1676
+ else:
1677
+ raise e
1678
+ except Exception as e2:
1679
+ print("Warning: failed to save model state_dict:", e2)
1680
+ try:
1681
+ torch.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
1682
+ except Exception:
1683
+ pass
1684
+ try:
1685
+ torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
1686
+ except Exception:
1687
+ pass
1688
+
1689
+ def _load_best_model(self):
1690
+ best_ckpt = self.state.best_model_checkpoint
1691
+ if not best_ckpt:
1692
+ return
1693
+ candidate = os.path.join(best_ckpt, "pytorch_model.bin")
1694
+ if not os.path.exists(candidate):
1695
+ candidate = os.path.join(best_ckpt, "model.bin")
1696
+ if not os.path.exists(candidate):
1697
+ candidate = None
1698
+ if candidate is None:
1699
+ print(f"CLTrainer._load_best_model(): no compatible pytorch_model.bin found in {best_ckpt}; skipping load.")
1700
+ return
1701
+ try:
1702
+ state_dict = torch.load(candidate, map_location=self.args.device)
1703
+ model_to_load = self.model.mm if hasattr(self.model, "mm") else self.model
1704
+ model_to_load.load_state_dict(state_dict, strict=False)
1705
+ print(f"CLTrainer: loaded best model state_dict from {candidate}")
1706
+ except Exception as e:
1707
+ print("CLTrainer._load_best_model: failed to load state_dict using torch.load:", e)
1708
+ return
1709
+
1710
+ callback = VerboseTrainingCallback(patience=10)
1711
+
1712
+ trainer = CLTrainer(
1713
+ model=hf_model,
1714
+ args=training_args,
1715
+ train_dataset=train_subset,
1716
+ eval_dataset=val_subset,
1717
+ data_collator=data_collator,
1718
+ callbacks=[callback],
1719
+ )
1720
+
1721
+ callback.trainer_ref = trainer
1722
+
1723
+ # Force HF Trainer to use our prebuilt PyTorch DataLoaders
1724
+ trainer.get_train_dataloader = lambda dataset=None: train_loader
1725
+ trainer.get_eval_dataloader = lambda eval_dataset=None: val_loader
1726
+
1727
+ training_args.metric_for_best_model = "eval_loss"
1728
+ training_args.greater_is_better = False
1729
+
1730
+ optimizer = torch.optim.AdamW(multimodal_model.parameters(), lr=training_args.learning_rate, weight_decay=training_args.weight_decay)
1731
+
1732
+ total_params = sum(p.numel() for p in multimodal_model.parameters())
1733
+ trainable_params = sum(p.numel() for p in multimodal_model.parameters() if p.requires_grad)
1734
+ non_trainable_params = total_params - trainable_params
1735
+
1736
+ print(f"\n📊 MODEL PARAMETERS:")
1737
+ print(f" Total Parameters: {total_params:,}")
1738
+ print(f" Trainable Parameters: {trainable_params:,}")
1739
+ print(f" Non-trainable Parameters: {non_trainable_params:,}")
1740
+
1741
+ def compute_metrics_wrapper(eval_pred):
1742
+ return evaluate_multimodal(multimodal_model, val_loader, device, mask_target="fp")
1743
+
1744
+ # ---------------------------
1745
+ # Clear any cached GPU memory before starting (helpful)
1746
+ if USE_CUDA:
1747
+ try:
1748
+ torch.cuda.empty_cache()
1749
+ except Exception:
1750
+ pass
1751
+
1752
+ # ---------------------------
1753
+ # Start training
1754
+ training_start_time = time.time()
1755
+ trainer.train()
1756
+ training_end_time = time.time()
1757
+
1758
+ # Save best
1759
+ BEST_MULTIMODAL_DIR = os.path.join(OUTPUT_DIR, "best")
1760
+ os.makedirs(BEST_MULTIMODAL_DIR, exist_ok=True)
1761
+
1762
+ try:
1763
+ best_ckpt = trainer.state.best_model_checkpoint
1764
+ if best_ckpt:
1765
+ multimodal_model.load_state_dict(torch.load(os.path.join(best_ckpt, "pytorch_model.bin"), map_location=device), strict=False)
1766
+ print(f"Loaded best checkpoint from {best_ckpt} into multimodal_model for final evaluation.")
1767
+ torch.save(multimodal_model.state_dict(), os.path.join(BEST_MULTIMODAL_DIR, "pytorch_model.bin"))
1768
+ print(f"✅ Saved best multimodal model to {os.path.join(BEST_MULTIMODAL_DIR, 'pytorch_model.bin')}")
1769
+ except Exception as e:
1770
+ print("Warning: failed to load/save best model from Trainer:", e)
1771
+
1772
+ # Final evaluation
1773
+ final_metrics = {}
1774
+ try:
1775
+ if trainer.state.best_model_checkpoint:
1776
+ trainer._load_best_model()
1777
+ final_metrics = trainer.evaluate(eval_dataset=val_subset)
1778
+ else:
1779
+ final_metrics = evaluate_multimodal(multimodal_model, val_loader, device, mask_target="fp")
1780
+ except Exception as e:
1781
+ print("Warning: final evaluation via trainer.evaluate failed, falling back to direct evaluate_multimodal:", e)
1782
+ final_metrics = evaluate_multimodal(multimodal_model, val_loader, device, mask_target="fp")
1783
+
1784
+ print("\n" + "="*80)
1785
+ print("🏁 FINAL TRAINING RESULTS")
1786
+ print("="*80)
1787
+ training_time = training_end_time - training_start_time
1788
+ print(f"Total Training Time: {training_time:.2f}s")
1789
+ best_ckpt = trainer.state.best_model_checkpoint if hasattr(trainer.state, 'best_model_checkpoint') else None
1790
+ if best_ckpt:
1791
+ print(f"Best Checkpoint: {best_ckpt}")
1792
+ else:
1793
+ print("Best Checkpoint: (none saved)")
1794
+
1795
+ hf_eval_loss = final_metrics.get('eval_loss', float('nan'))
1796
+ hf_eval_acc = final_metrics.get('eval_accuracy', 0.0)
1797
+ hf_eval_f1 = final_metrics.get('eval_f1_weighted', 0.0)
1798
+ print(f"Val Loss (HF reported / trainer.evaluate): {hf_eval_loss:.4f}")
1799
+ print(f"Val Acc (CL evaluator): {hf_eval_acc:.4f}")
1800
+ print(f"Val F1 Weighted (CL evaluator): {hf_eval_f1:.4f}")
1801
+ print(f"Total Trainable Params: {trainable_params:,}")
1802
+ print(f"Total Non-trainable Params: {non_trainable_params:,}")
1803
+ print("="*80)