manpreet88 commited on
Commit
64eec2b
·
1 Parent(s): c50f0de

Update DeBERTav2.py

Browse files
Files changed (1) hide show
  1. PolyFusion/DeBERTav2.py +351 -218
PolyFusion/DeBERTav2.py CHANGED
@@ -1,207 +1,252 @@
 
 
 
 
1
 
2
  import os
3
- os.environ["CUDA_VISIBLE_DEVICES"] = "0"
4
-
5
  import time
6
- import random
7
  import json
8
- import torch
9
- import pandas as pd
10
- import numpy as np
11
- from transformers import DebertaV2Config, DebertaV2ForMaskedLM, Trainer, TrainingArguments
12
- from transformers import DebertaV2Tokenizer, DataCollatorForLanguageModeling
13
- from sklearn.model_selection import train_test_split
14
- from datasets import Dataset, DatasetDict, load_dataset
15
- from sentencepiece import SentencePieceTrainer, SentencePieceProcessor
16
- from sklearn.metrics import f1_score, accuracy_score
17
- import matplotlib.pyplot as plt
18
- from collections import defaultdict
19
- from transformers.trainer_callback import TrainerCallback
20
  import shutil
21
- import sentencepiece as spm
22
-
23
- # === 1. Load Data ===
24
- df = pd.read_csv("Polymer_Foundational_Model/Datasets/polymer_structures_unified.csv", nrows=5000000, engine='python')
25
- psmiles_list = df["psmiles"].astype(str).tolist()
26
-
27
- # === 2. Train/Val Split ===
28
- train_psmiles, val_psmiles = train_test_split(psmiles_list, test_size=0.2, random_state=42)
29
-
30
- # === 3. SentencePiece Tokenizer Training ===
31
- # Write training text required by SentencePiece
32
- train_txt = "generated_polymer_smiles_5M.txt"
33
- with open(train_txt, "w", encoding="utf-8") as f:
34
- for s in train_psmiles:
35
- f.write(s.strip() + "\n")
36
-
37
- # Special tokens and element tokens as provided
38
- elements = ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', 'Ds', 'Rg', 'Cn', 'Nh', 'Fl', 'Mc', 'Lv', 'Ts', 'Og', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr']
39
- small_elements = [i.lower() for i in elements]
40
-
41
- special_tokens = [
42
- "<pad>",
43
- "<mask>",
44
- "[*]",
45
- "(", ")", "=", "@", "#",
46
- "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
47
- "-", "+",
48
- "/", "\\",
49
- "%", "[", "]",
50
- ]
51
- special_tokens += elements + small_elements
52
-
53
- spm_model_prefix = "spm_5M"
54
- if not os.path.isfile(spm_model_prefix + ".model"):
55
- spm.SentencePieceTrainer.train(
56
- input=train_txt,
57
- model_prefix=spm_model_prefix,
58
- vocab_size=265,
59
- input_sentence_size=5_000_000,
60
- character_coverage=1.0,
61
- user_defined_symbols=special_tokens
 
 
 
62
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
- # Note: this produces spm.model and spm.vocab in the working directory
65
-
66
- # === 4. Load HuggingFace Tokenizer (expects tokenizer files in './') ===
67
- # Use the SentencePiece model we produced as the vocab file for DebertaV2Tokenizer.
68
- # (This keeps DebertaV2Tokenizer usage while explicitly referencing the spm model file.)
69
- tokenizer = DebertaV2Tokenizer(vocab_file=spm_model_prefix + ".model", do_lower_case=False)
70
-
71
- # Ensure special tokens are set (if they already exist this will be a no-op)
72
- tokenizer.add_special_tokens({"pad_token": "<pad>", "mask_token": "<mask>"})
73
-
74
- # === 5. Create HF datasets and tokenize (batched) ===
75
- hf_train = Dataset.from_dict({"text": train_psmiles})
76
- hf_val = Dataset.from_dict({"text": val_psmiles})
77
-
78
- def tokenize_batch(examples):
79
- # Tokenize text -> return input_ids and attention_mask
80
- return tokenizer(examples["text"], truncation=True, padding="max_length", max_length=128)
81
-
82
- # Batched tokenization with provided params (kept num_proc and batch_size as originally used)
83
- train_tok = hf_train.map(tokenize_batch, batched=True, batch_size=10_000, num_proc=10)
84
- val_tok = hf_val.map(tokenize_batch, batched=True, batch_size=10_000, num_proc=10)
85
-
86
- dataset_dict = DatasetDict({"train": train_tok, "test": val_tok})
87
- dataset_dict.save_to_disk("dataset_tokenized_all")
88
-
89
- # === 6. Load tokenized dataset for training and set format for PyTorch ===
90
- dataset_all = DatasetDict.load_from_disk("dataset_tokenized_all")
91
- dataset_train = dataset_all["train"]
92
- dataset_test = dataset_all["test"]
93
-
94
- # Keep only input_ids and attention_mask for Trainer; DataCollator will create labels
95
- dataset_train.set_format(type="torch", columns=["input_ids", "attention_mask"])
96
- dataset_test.set_format(type="torch", columns=["input_ids", "attention_mask"])
97
-
98
- # === 7. Data collator for MLM ===
99
- data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15)
100
-
101
- # === 8. Model Config and Model ===
102
- # Use tokenizer length for vocab_size and pad token id from tokenizer
103
- vocab_size = len(tokenizer)
104
- pad_token_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0
105
-
106
- config = DebertaV2Config(
107
- vocab_size=vocab_size,
108
- hidden_size=600,
109
- num_attention_heads=12,
110
- num_hidden_layers=12,
111
- intermediate_size=512,
112
- pad_token_id=pad_token_id
113
- )
114
-
115
- model = DebertaV2ForMaskedLM(config)
116
- # Resize token embeddings to match tokenizer (in case add_special_tokens added tokens)
117
- model.resize_token_embeddings(len(tokenizer))
118
-
119
- device = "cuda:0" if torch.cuda.is_available() else "cpu"
120
- model.to(device)
121
-
122
- # === 9. Training Arguments ===
123
- # NOTE: per your instruction, leaving `eval_strategy` as originally written (not changing to evaluation_strategy).
124
- training_args = TrainingArguments(
125
- output_dir="./polybert_output_5M",
126
- overwrite_output_dir=True,
127
- num_train_epochs=25,
128
- per_device_train_batch_size=16,
129
- per_device_eval_batch_size=8,
130
- eval_accumulation_steps=1000,
131
- gradient_accumulation_steps=4,
132
- eval_strategy="epoch", # kept as in your original code (you asked to keep suggestion 4 unchanged)
133
- logging_strategy="steps",
134
- logging_steps=500,
135
- logging_first_step=True,
136
- save_strategy="no",
137
- learning_rate=1e-4,
138
- weight_decay=0.01,
139
- fp16=torch.cuda.is_available(),
140
- report_to=[],
141
- disable_tqdm=False,
142
- )
143
-
144
- # === 10. Callback (printing/metrics logic to exactly match the first file) ===
145
- class EpochMetricsCallback(TrainerCallback):
146
- def __init__(self, tokenizer_model_path):
147
- super().__init__()
148
- # Load SentencePiece processor properly
149
- self.sp = SentencePieceProcessor()
150
- self.sp.Load(tokenizer_model_path)
151
  self.tokenizer_model_path = tokenizer_model_path
 
 
152
  self.best_val_loss = float("inf")
153
  self.best_epoch = 0
154
  self.epochs_no_improve = 0
155
- self.patience = 10
 
156
  self.all_epochs = []
157
  self.best_val_f1 = None
158
  self.best_val_accuracy = None
159
  self.best_perplexity = None
160
- # trainer reference will be set after Trainer instantiation
161
  self.trainer_ref = None
162
- # temporary storage for train loss captured at epoch end
163
  self._last_train_loss = None
164
 
165
- def token_id_to_str(self, token_id):
166
- try:
167
- if token_id == self.sp.pad_id():
168
- return "[PAD]"
169
- if token_id == self.sp.unk_id():
170
- return "[UNK]"
171
- except Exception:
172
- pass
173
- return self.sp.id_to_piece(token_id)
174
 
175
- def save_model(self, trainer_obj, suffix):
176
  if trainer_obj is None:
177
  return
178
- model_dir = f"./polybert_output_5M/{suffix}"
179
  os.makedirs(model_dir, exist_ok=True)
180
  trainer_obj.model.save_pretrained(model_dir)
181
  try:
182
- shutil.copyfile(self.tokenizer_model_path, f"{model_dir}/tokenizer.model")
183
  except Exception:
184
  pass
185
 
186
- # Keep on_epoch_end minimal: only capture the most recent train loss
187
- def on_epoch_end(self, args, state, control, **kwargs):
188
  train_loss = None
189
  for log in reversed(state.log_history):
190
  if "loss" in log and float(log.get("loss", 0)) != 0.0:
191
- # pick the most recent loss entry
192
  train_loss = log["loss"]
193
  break
194
  self._last_train_loss = train_loss
195
- # DO NOT print eval values here — evaluation hasn't necessarily run yet.
196
 
197
- # Called AFTER Trainer runs evaluation; metrics is provided by Trainer
198
- def on_evaluate(self, args, state, control, metrics=None, **kwargs):
 
199
  eval_metrics = metrics or {}
200
  eval_loss = eval_metrics.get("eval_loss")
201
  eval_f1 = eval_metrics.get("eval_f1")
202
  eval_accuracy = eval_metrics.get("eval_accuracy", None)
203
 
204
- # retrieve most recent train loss captured at epoch end (could be None)
205
  train_loss = self._last_train_loss
206
 
207
  epoch_data = {
@@ -214,7 +259,6 @@ class EpochMetricsCallback(TrainerCallback):
214
  }
215
  self.all_epochs.append(epoch_data)
216
 
217
- # Save best model (use stored trainer_ref if available)
218
  if eval_loss is not None and eval_loss < self.best_val_loss - 1e-6:
219
  self.best_val_loss = eval_loss
220
  self.best_epoch = state.epoch
@@ -222,7 +266,7 @@ class EpochMetricsCallback(TrainerCallback):
222
  self.best_val_f1 = eval_f1
223
  self.best_val_accuracy = eval_accuracy
224
  self.best_perplexity = np.exp(eval_loss) if eval_loss is not None else None
225
- self.save_model(self.trainer_ref, "best")
226
  else:
227
  self.epochs_no_improve += 1
228
 
@@ -230,8 +274,9 @@ class EpochMetricsCallback(TrainerCallback):
230
  print(f"Early stopping: no improvement in val_loss for {self.patience} epochs.")
231
  control.should_training_stop = True
232
 
233
- total_params = sum(p.numel() for p in self.trainer_ref.model.parameters()) if self.trainer_ref is not None else sum(p.numel() for p in model.parameters())
234
- trainable_params = sum(p.numel() for p in (self.trainer_ref.model.parameters() if self.trainer_ref is not None else model.parameters()) if p.requires_grad)
 
235
  print(f"\n=== Epoch {int(state.epoch)}/{args.num_train_epochs} ===")
236
  print(f"Train Loss: {train_loss:.4f}" if train_loss is not None else "Train Loss: None")
237
  print(f"Validation Loss: {eval_loss:.4f}" if eval_loss is not None else "Validation Loss: None")
@@ -245,67 +290,155 @@ class EpochMetricsCallback(TrainerCallback):
245
  print(f"Trainable Params: {trainable_params}")
246
  print(f"No improvement count:{self.epochs_no_improve}/{self.patience}")
247
 
248
- def on_train_end(self, args, state, control, **kwargs):
249
  print("\n=== Model saved ===")
250
- print(f"Best model (epoch {int(self.best_epoch)}, val_loss={self.best_val_loss:.4f}): ./polybert_output_5M/best/")
 
251
 
252
- # === 11. Metrics function (fixed for MLM shapes and -100 masking) ===
253
  def compute_metrics(eval_pred):
254
- logits, labels = eval_pred # logits: (batch, seq_len, vocab_size), labels: (batch, seq_len)
255
- # Flatten
 
 
 
256
  flat_logits = logits.reshape(-1, logits.shape[-1])
257
  flat_labels = labels.reshape(-1)
258
  mask = flat_labels != -100
 
259
  if mask.sum() == 0:
260
  return {"eval_f1": 0.0, "eval_accuracy": 0.0}
 
261
  masked_logits = flat_logits[mask]
262
  masked_labels = flat_labels[mask]
263
  preds = np.argmax(masked_logits, axis=-1)
 
264
  f1 = f1_score(masked_labels, preds, average="weighted")
265
  accuracy = np.mean(masked_labels == preds)
266
  return {"eval_f1": f1, "eval_accuracy": accuracy}
267
 
268
- # === 12. Trainer and training ===
269
- start_time = time.time()
270
- callback = EpochMetricsCallback(tokenizer_model_path=spm_model_prefix + ".model")
271
-
272
- trainer = Trainer(
273
- model=model,
274
- args=training_args,
275
- train_dataset=dataset_train, # fixed name
276
- eval_dataset=dataset_test, # fixed name
277
- data_collator=data_collator, # ensure MLM labels are created
278
- compute_metrics=compute_metrics,
279
- callbacks=[callback],
280
- )
281
-
282
- # Attach trainer reference to callback so it can save model
283
- callback.trainer_ref = trainer
284
-
285
- train_output = trainer.train()
286
- total_time = time.time() - start_time
287
-
288
- # === 9. Final Results Report ===
289
- print(f"\n=== Final Results ===")
290
- print(f"Total Training Time (s): {total_time:.2f}")
291
- print(f"Best Validation Loss: {callback.best_val_loss:.4f}")
292
- if callback.best_val_f1 is not None:
293
- print(f"Best Validation F1: {callback.best_val_f1:.4f}")
294
- else:
295
- print("Best Validation F1: None")
296
- if callback.best_val_accuracy is not None:
297
- print(f"Best Validation Accuracy: {callback.best_val_accuracy:.4f}")
298
- else:
299
- print("Best Validation Accuracy: None")
300
- if callback.best_perplexity is not None:
301
- print(f"Best Perplexity: {callback.best_perplexity:.2f}")
302
- else:
303
- print("Best Perplexity: None")
304
- print(f"Best Model Epoch: {int(callback.best_epoch)}")
305
- print(f"Final Training Loss: {train_output.training_loss:.4f}")
306
- total_params = sum(p.numel() for p in model.parameters())
307
- trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
308
- non_trainable_params = total_params - trainable_params
309
- print(f"Total Parameters: {total_params}")
310
- print(f"Trainable Parameters: {trainable_params}")
311
- print(f"Non-trainable Parameters: {non_trainable_params}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DeBERTav2.py
2
+ """
3
+ DeBERTaV2 masked language modeling pretraining for polymer SMILES (PSMILES).
4
+ """
5
 
6
  import os
 
 
7
  import time
 
8
  import json
 
 
 
 
 
 
 
 
 
 
 
 
9
  import shutil
10
+ import argparse
11
+ import warnings
12
+ from typing import Optional, List
13
+
14
+ warnings.filterwarnings("ignore")
15
+
16
+ def set_cuda_visible_devices(gpu: str = "0") -> None:
17
+ """Set CUDA_VISIBLE_DEVICES before importing torch/transformers heavy modules."""
18
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
19
+
20
+ def parse_args() -> argparse.Namespace:
21
+ """CLI arguments for paths and key training/data settings."""
22
+ parser = argparse.ArgumentParser(description="DeBERTaV2 MLM pretraining for polymer pSMILES.")
23
+ parser.add_argument("--gpu", type=str, default="0", help="CUDA_VISIBLE_DEVICES value.")
24
+ parser.add_argument(
25
+ "--csv_file",
26
+ type=str,
27
+ default="/path/to/polymer_structures_unified.csv",
28
+ help="Path to input CSV containing a 'psmiles' column.",
29
+ )
30
+ parser.add_argument("--nrows", type=int, default=5_000_000, help="Number of rows to read from CSV.")
31
+ parser.add_argument(
32
+ "--train_txt",
33
+ type=str,
34
+ default="/path/to/generated_polymer_smiles_5M.txt",
35
+ help="Path to write SentencePiece training text (one SMILES per line).",
36
+ )
37
+ parser.add_argument(
38
+ "--spm_prefix",
39
+ type=str,
40
+ default="/path/to/spm_5M",
41
+ help="SentencePiece model prefix (produces <prefix>.model and <prefix>.vocab).",
42
+ )
43
+ parser.add_argument(
44
+ "--tokenized_dataset_dir",
45
+ type=str,
46
+ default="/path/to/dataset_tokenized_all",
47
+ help="Directory to save/load tokenized HF dataset.",
48
+ )
49
+ parser.add_argument(
50
+ "--output_dir",
51
+ type=str,
52
+ default="/path/to/polybert_output_5M",
53
+ help="Trainer output directory (will contain best/).",
54
  )
55
+ return parser.parse_args()
56
+
57
+
58
+ def load_psmiles_from_csv(csv_file: str, nrows: int) -> List[str]:
59
+ """Load pSMILES strings from CSV."""
60
+ import pandas as pd
61
+
62
+ df = pd.read_csv(csv_file, nrows=nrows, engine="python")
63
+ return df["psmiles"].astype(str).tolist()
64
+
65
+
66
+ def train_val_split(psmiles_list: List[str], test_size: float = 0.2, random_state: int = 42):
67
+ """Split pSMILES into train/val lists."""
68
+ from sklearn.model_selection import train_test_split
69
+
70
+ return train_test_split(psmiles_list, test_size=test_size, random_state=random_state)
71
+
72
+
73
+ def write_sentencepiece_training_text(train_psmiles: List[str], train_txt: str) -> None:
74
+ """Write one pSMILES per line for SentencePiece training."""
75
+ os.makedirs(os.path.dirname(os.path.abspath(train_txt)), exist_ok=True)
76
+ with open(train_txt, "w", encoding="utf-8") as f:
77
+ for s in train_psmiles:
78
+ f.write(s.strip() + "\n")
79
+
80
+
81
+ def get_special_tokens() -> List[str]:
82
+ """
83
+ Special tokens + element symbols (upper and lower case) used as user-defined symbols
84
+ for SentencePiece.
85
+ """
86
+ elements = [
87
+ "H","He","Li","Be","B","C","N","O","F","Ne","Na","Mg","Al","Si","P","S","Cl","Ar","K","Ca","Sc","Ti","V","Cr","Mn",
88
+ "Fe","Co","Ni","Cu","Zn","Ga","Ge","As","Se","Br","Kr","Rb","Sr","Y","Zr","Nb","Mo","Tc","Ru","Rh","Pd","Ag","Cd",
89
+ "In","Sn","Sb","Te","I","Xe","Cs","Ba","La","Hf","Ta","W","Re","Os","Ir","Pt","Au","Hg","Tl","Pb","Bi","Po","At",
90
+ "Rn","Fr","Ra","Ac","Rf","Db","Sg","Bh","Hs","Mt","Ds","Rg","Cn","Nh","Fl","Mc","Lv","Ts","Og","Ce","Pr","Nd","Pm",
91
+ "Sm","Eu","Gd","Tb","Dy","Ho","Er","Tm","Yb","Lu","Th","Pa","U","Np","Pu","Am","Cm","Bk","Cf","Es","Fm","Md","No","Lr"
92
+ ]
93
+ small_elements = [i.lower() for i in elements]
94
+
95
+ special_tokens = [
96
+ "<pad>",
97
+ "<mask>",
98
+ "[*]",
99
+ "(", ")", "=", "@", "#",
100
+ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
101
+ "-", "+",
102
+ "/", "\\",
103
+ "%", "[", "]",
104
+ ]
105
+ special_tokens += elements + small_elements
106
+ return special_tokens
107
+
108
+
109
+ def train_sentencepiece_if_needed(train_txt: str, spm_model_prefix: str, vocab_size: int = 265) -> str:
110
+ """
111
+ Train SentencePiece model if <prefix>.model does not exist.
112
+ Returns path to the .model file.
113
+ """
114
+ import sentencepiece as spm
115
+
116
+ model_path = spm_model_prefix + ".model"
117
+ os.makedirs(os.path.dirname(os.path.abspath(spm_model_prefix)), exist_ok=True)
118
+
119
+ if not os.path.isfile(model_path):
120
+ spm.SentencePieceTrainer.train(
121
+ input=train_txt,
122
+ model_prefix=spm_model_prefix,
123
+ vocab_size=vocab_size,
124
+ input_sentence_size=5_000_000,
125
+ character_coverage=1.0,
126
+ user_defined_symbols=get_special_tokens(),
127
+ )
128
+ return model_path
129
+
130
+
131
+ def build_tokenizer(spm_model_path: str):
132
+ """Create a DebertaV2Tokenizer backed by a SentencePiece model."""
133
+ from transformers import DebertaV2Tokenizer
134
+
135
+ tokenizer = DebertaV2Tokenizer(vocab_file=spm_model_path, do_lower_case=False)
136
+ tokenizer.add_special_tokens({"pad_token": "<pad>", "mask_token": "<mask>"})
137
+ return tokenizer
138
+
139
+
140
+ def tokenize_and_save_dataset(train_psmiles: List[str], val_psmiles: List[str], tokenizer, save_dir: str) -> None:
141
+ """Tokenize train/val and persist the DatasetDict to disk."""
142
+ from datasets import Dataset, DatasetDict
143
+
144
+ hf_train = Dataset.from_dict({"text": train_psmiles})
145
+ hf_val = Dataset.from_dict({"text": val_psmiles})
146
+
147
+ def tokenize_batch(examples):
148
+ return tokenizer(examples["text"], truncation=True, padding="max_length", max_length=128)
149
+
150
+ train_tok = hf_train.map(tokenize_batch, batched=True, batch_size=10_000, num_proc=10)
151
+ val_tok = hf_val.map(tokenize_batch, batched=True, batch_size=10_000, num_proc=10)
152
+
153
+ dataset_dict = DatasetDict({"train": train_tok, "test": val_tok})
154
+ os.makedirs(save_dir, exist_ok=True)
155
+ dataset_dict.save_to_disk(save_dir)
156
+
157
+
158
+ def load_tokenized_dataset(tokenized_dir: str):
159
+ """Load tokenized DatasetDict and set torch formats."""
160
+ from datasets import DatasetDict
161
+
162
+ dataset_all = DatasetDict.load_from_disk(tokenized_dir)
163
+ dataset_train = dataset_all["train"]
164
+ dataset_test = dataset_all["test"]
165
+
166
+ dataset_train.set_format(type="torch", columns=["input_ids", "attention_mask"])
167
+ dataset_test.set_format(type="torch", columns=["input_ids", "attention_mask"])
168
+ return dataset_train, dataset_test
169
+
170
+
171
+ class EpochMetricsCallback:
172
+ """
173
+ TrainerCallback that:
174
+ - Tracks best validation loss
175
+ - Implements early stopping on val_loss with patience
176
+ - Saves best model + tokenizer.model copy
177
+ - Prints epoch-level stats
178
+ """
179
+
180
+ # NOTE: We import TrainerCallback lazily to keep module import minimal in helpers.
181
+ def __init__(self, tokenizer_model_path: str, output_dir: str, patience: int = 10):
182
+ from transformers.trainer_callback import TrainerCallback
183
+ from sentencepiece import SentencePieceProcessor
184
+
185
+ class _CB(TrainerCallback):
186
+ def __init__(self, outer):
187
+ super().__init__()
188
+ self.outer = outer
189
+
190
+ def on_epoch_end(self, args, state, control, **kwargs):
191
+ self.outer._on_epoch_end(args, state, control, **kwargs)
192
+
193
+ def on_evaluate(self, args, state, control, metrics=None, **kwargs):
194
+ self.outer._on_evaluate(args, state, control, metrics=metrics, **kwargs)
195
+
196
+ def on_train_end(self, args, state, control, **kwargs):
197
+ self.outer._on_train_end(args, state, control, **kwargs)
198
+
199
+ self._cb_cls = _CB
200
+ self._sp = SentencePieceProcessor()
201
+ self._sp.Load(tokenizer_model_path)
202
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  self.tokenizer_model_path = tokenizer_model_path
204
+ self.output_dir = output_dir
205
+
206
  self.best_val_loss = float("inf")
207
  self.best_epoch = 0
208
  self.epochs_no_improve = 0
209
+ self.patience = patience
210
+
211
  self.all_epochs = []
212
  self.best_val_f1 = None
213
  self.best_val_accuracy = None
214
  self.best_perplexity = None
215
+
216
  self.trainer_ref = None
 
217
  self._last_train_loss = None
218
 
219
+ def as_trainer_callback(self):
220
+ """Return an instance that HuggingFace Trainer can register."""
221
+ return self._cb_cls(self)
 
 
 
 
 
 
222
 
223
+ def _save_model(self, trainer_obj, suffix: str) -> None:
224
  if trainer_obj is None:
225
  return
226
+ model_dir = os.path.join(self.output_dir, suffix)
227
  os.makedirs(model_dir, exist_ok=True)
228
  trainer_obj.model.save_pretrained(model_dir)
229
  try:
230
+ shutil.copyfile(self.tokenizer_model_path, os.path.join(model_dir, "tokenizer.model"))
231
  except Exception:
232
  pass
233
 
234
+ def _on_epoch_end(self, args, state, control, **kwargs):
 
235
  train_loss = None
236
  for log in reversed(state.log_history):
237
  if "loss" in log and float(log.get("loss", 0)) != 0.0:
 
238
  train_loss = log["loss"]
239
  break
240
  self._last_train_loss = train_loss
 
241
 
242
+ def _on_evaluate(self, args, state, control, metrics=None, **kwargs):
243
+ import numpy as np
244
+
245
  eval_metrics = metrics or {}
246
  eval_loss = eval_metrics.get("eval_loss")
247
  eval_f1 = eval_metrics.get("eval_f1")
248
  eval_accuracy = eval_metrics.get("eval_accuracy", None)
249
 
 
250
  train_loss = self._last_train_loss
251
 
252
  epoch_data = {
 
259
  }
260
  self.all_epochs.append(epoch_data)
261
 
 
262
  if eval_loss is not None and eval_loss < self.best_val_loss - 1e-6:
263
  self.best_val_loss = eval_loss
264
  self.best_epoch = state.epoch
 
266
  self.best_val_f1 = eval_f1
267
  self.best_val_accuracy = eval_accuracy
268
  self.best_perplexity = np.exp(eval_loss) if eval_loss is not None else None
269
+ self._save_model(self.trainer_ref, "best")
270
  else:
271
  self.epochs_no_improve += 1
272
 
 
274
  print(f"Early stopping: no improvement in val_loss for {self.patience} epochs.")
275
  control.should_training_stop = True
276
 
277
+ total_params = sum(p.numel() for p in self.trainer_ref.model.parameters()) if self.trainer_ref is not None else 0
278
+ trainable_params = sum(p.numel() for p in self.trainer_ref.model.parameters() if p.requires_grad) if self.trainer_ref is not None else 0
279
+
280
  print(f"\n=== Epoch {int(state.epoch)}/{args.num_train_epochs} ===")
281
  print(f"Train Loss: {train_loss:.4f}" if train_loss is not None else "Train Loss: None")
282
  print(f"Validation Loss: {eval_loss:.4f}" if eval_loss is not None else "Validation Loss: None")
 
290
  print(f"Trainable Params: {trainable_params}")
291
  print(f"No improvement count:{self.epochs_no_improve}/{self.patience}")
292
 
293
+ def _on_train_end(self, args, state, control, **kwargs):
294
  print("\n=== Model saved ===")
295
+ print(f"Best model (epoch {int(self.best_epoch)}, val_loss={self.best_val_loss:.4f}): {os.path.join(self.output_dir, 'best')}/")
296
+
297
 
 
298
  def compute_metrics(eval_pred):
299
+ """Metrics for MLM: accuracy + weighted F1 computed only on masked (-100 excluded) positions."""
300
+ import numpy as np
301
+ from sklearn.metrics import f1_score
302
+
303
+ logits, labels = eval_pred
304
  flat_logits = logits.reshape(-1, logits.shape[-1])
305
  flat_labels = labels.reshape(-1)
306
  mask = flat_labels != -100
307
+
308
  if mask.sum() == 0:
309
  return {"eval_f1": 0.0, "eval_accuracy": 0.0}
310
+
311
  masked_logits = flat_logits[mask]
312
  masked_labels = flat_labels[mask]
313
  preds = np.argmax(masked_logits, axis=-1)
314
+
315
  f1 = f1_score(masked_labels, preds, average="weighted")
316
  accuracy = np.mean(masked_labels == preds)
317
  return {"eval_f1": f1, "eval_accuracy": accuracy}
318
 
319
+
320
+ def build_model_and_trainer(tokenizer, dataset_train, dataset_test, spm_model_path: str, output_dir: str):
321
+ """Construct model, training args, callback, and Trainer."""
322
+ import torch
323
+ import numpy as np
324
+ from transformers import DebertaV2Config, DebertaV2ForMaskedLM, Trainer, TrainingArguments
325
+ from transformers import DataCollatorForLanguageModeling
326
+
327
+ data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15)
328
+
329
+ vocab_size = len(tokenizer)
330
+ pad_token_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0
331
+
332
+ config = DebertaV2Config(
333
+ vocab_size=vocab_size,
334
+ hidden_size=600,
335
+ num_attention_heads=12,
336
+ num_hidden_layers=12,
337
+ intermediate_size=512,
338
+ pad_token_id=pad_token_id,
339
+ )
340
+
341
+ model = DebertaV2ForMaskedLM(config)
342
+ model.resize_token_embeddings(len(tokenizer))
343
+
344
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
345
+ model.to(device)
346
+
347
+ training_args = TrainingArguments(
348
+ output_dir=output_dir,
349
+ overwrite_output_dir=True,
350
+ num_train_epochs=25,
351
+ per_device_train_batch_size=16,
352
+ per_device_eval_batch_size=8,
353
+ eval_accumulation_steps=1000,
354
+ gradient_accumulation_steps=4,
355
+ eval_strategy="epoch", # kept exactly as provided
356
+ logging_strategy="steps",
357
+ logging_steps=500,
358
+ logging_first_step=True,
359
+ save_strategy="no",
360
+ learning_rate=1e-4,
361
+ weight_decay=0.01,
362
+ fp16=torch.cuda.is_available(),
363
+ report_to=[],
364
+ disable_tqdm=False,
365
+ )
366
+
367
+ callback_wrapper = EpochMetricsCallback(tokenizer_model_path=spm_model_path, output_dir=output_dir, patience=10)
368
+ trainer = Trainer(
369
+ model=model,
370
+ args=training_args,
371
+ train_dataset=dataset_train,
372
+ eval_dataset=dataset_test,
373
+ data_collator=data_collator,
374
+ compute_metrics=compute_metrics,
375
+ callbacks=[callback_wrapper.as_trainer_callback()],
376
+ )
377
+
378
+ callback_wrapper.trainer_ref = trainer
379
+ return model, trainer, callback_wrapper
380
+
381
+
382
+ def run_training(csv_file: str, nrows: int, train_txt: str, spm_prefix: str, tokenized_dir: str, output_dir: str) -> None:
383
+ """End-to-end: load data, train tokenizer (if needed), tokenize, train model, print final report."""
384
+ import torch
385
+
386
+ psmiles_list = load_psmiles_from_csv(csv_file, nrows=nrows)
387
+ train_psmiles, val_psmiles = train_val_split(psmiles_list, test_size=0.2, random_state=42)
388
+
389
+ write_sentencepiece_training_text(train_psmiles, train_txt)
390
+ spm_model_path = train_sentencepiece_if_needed(train_txt, spm_prefix, vocab_size=265)
391
+
392
+ tokenizer = build_tokenizer(spm_model_path)
393
+
394
+ # Tokenize and save dataset (always matching your original behavior)
395
+ tokenize_and_save_dataset(train_psmiles, val_psmiles, tokenizer, tokenized_dir)
396
+
397
+ dataset_train, dataset_test = load_tokenized_dataset(tokenized_dir)
398
+
399
+ model, trainer, callback = build_model_and_trainer(
400
+ tokenizer=tokenizer,
401
+ dataset_train=dataset_train,
402
+ dataset_test=dataset_test,
403
+ spm_model_path=spm_model_path,
404
+ output_dir=output_dir,
405
+ )
406
+
407
+ start_time = time.time()
408
+ train_output = trainer.train()
409
+ total_time = time.time() - start_time
410
+
411
+ # Final report
412
+ print(f"\n=== Final Results ===")
413
+ print(f"Total Training Time (s): {total_time:.2f}")
414
+ print(f"Best Validation Loss: {callback.best_val_loss:.4f}")
415
+ print(f"Best Validation F1: {callback.best_val_f1:.4f}" if callback.best_val_f1 is not None else "Best Validation F1: None")
416
+ print(f"Best Validation Accuracy: {callback.best_val_accuracy:.4f}" if callback.best_val_accuracy is not None else "Best Validation Accuracy: None")
417
+ print(f"Best Perplexity: {callback.best_perplexity:.2f}" if callback.best_perplexity is not None else "Best Perplexity: None")
418
+ print(f"Best Model Epoch: {int(callback.best_epoch)}")
419
+ print(f"Final Training Loss: {train_output.training_loss:.4f}")
420
+
421
+ total_params = sum(p.numel() for p in model.parameters())
422
+ trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
423
+ non_trainable_params = total_params - trainable_params
424
+ print(f"Total Parameters: {total_params}")
425
+ print(f"Trainable Parameters: {trainable_params}")
426
+ print(f"Non-trainable Parameters: {non_trainable_params}")
427
+
428
+
429
+ def main():
430
+ args = parse_args()
431
+ set_cuda_visible_devices(args.gpu)
432
+
433
+ run_training(
434
+ csv_file=args.csv_file,
435
+ nrows=args.nrows,
436
+ train_txt=args.train_txt,
437
+ spm_prefix=args.spm_prefix,
438
+ tokenized_dir=args.tokenized_dataset_dir,
439
+ output_dir=args.output_dir,
440
+ )
441
+
442
+
443
+ if __name__ == "__main__":
444
+ main()