Update generation test and upload continue from checkpoint train
Browse files- train_withmtp.py +7 -7
- train_withmtp_cont.py +502 -0
train_withmtp.py
CHANGED
|
@@ -433,22 +433,22 @@ def main():
|
|
| 433 |
model.set_mtp_training(False)
|
| 434 |
gen = model.generate(
|
| 435 |
input_ids,
|
| 436 |
-
max_length=
|
| 437 |
-
top_k=
|
| 438 |
-
top_p=
|
| 439 |
-
temperature=
|
| 440 |
-
do_sample=
|
| 441 |
pad_token_id=tokenizer.pad_token_id,
|
| 442 |
eos_token_id=tokenizer.eos_token_id,
|
| 443 |
-
num_return_sequences=
|
| 444 |
)
|
| 445 |
for i, sequence in enumerate(gen):
|
| 446 |
result = tokenizer.decode(sequence, skip_special_tokens=True)
|
| 447 |
print(f"Generated SELFIES {i+1}: {result}")
|
| 448 |
print("\n--- MTP Analysis Test ---")
|
| 449 |
-
model.set_mtp_training(True)
|
| 450 |
test_smiles = "[C]"
|
| 451 |
test_input = tokenizer(test_smiles, return_tensors="pt", add_special_tokens=True).to(device)
|
|
|
|
| 452 |
with torch.no_grad():
|
| 453 |
outputs = model(**test_input)
|
| 454 |
if hasattr(model, 'mtp_head') and hasattr(model.mtp_head, 'prediction_heads'):
|
|
|
|
| 433 |
model.set_mtp_training(False)
|
| 434 |
gen = model.generate(
|
| 435 |
input_ids,
|
| 436 |
+
max_length=25,
|
| 437 |
+
top_k=50,
|
| 438 |
+
top_p=0.9,
|
| 439 |
+
temperature=1.0,
|
| 440 |
+
do_sample=True,
|
| 441 |
pad_token_id=tokenizer.pad_token_id,
|
| 442 |
eos_token_id=tokenizer.eos_token_id,
|
| 443 |
+
num_return_sequences=3,
|
| 444 |
)
|
| 445 |
for i, sequence in enumerate(gen):
|
| 446 |
result = tokenizer.decode(sequence, skip_special_tokens=True)
|
| 447 |
print(f"Generated SELFIES {i+1}: {result}")
|
| 448 |
print("\n--- MTP Analysis Test ---")
|
|
|
|
| 449 |
test_smiles = "[C]"
|
| 450 |
test_input = tokenizer(test_smiles, return_tensors="pt", add_special_tokens=True).to(device)
|
| 451 |
+
test_input = {k: v for k, v in test_input.items() if k != 'token_type_ids'} # Remove token_type_ids
|
| 452 |
with torch.no_grad():
|
| 453 |
outputs = model(**test_input)
|
| 454 |
if hasattr(model, 'mtp_head') and hasattr(model.mtp_head, 'prediction_heads'):
|
train_withmtp_cont.py
ADDED
|
@@ -0,0 +1,502 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ========================
|
| 2 |
+
# Train with NTP + MTP
|
| 3 |
+
# Updated for ChemQ3MTP structure
|
| 4 |
+
# by gbyuvd
|
| 5 |
+
# ========================
|
| 6 |
+
|
| 7 |
+
# train_withmtp.py
|
| 8 |
+
import sys
|
| 9 |
+
import os
|
| 10 |
+
# Add the current directory to Python path so it can find your modules
|
| 11 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn as nn
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
import json
|
| 17 |
+
from typing import List, Union, Optional, Tuple, Dict, Any
|
| 18 |
+
from transformers.tokenization_utils_base import BatchEncoding
|
| 19 |
+
from transformers import Trainer, TrainingArguments, DataCollatorForLanguageModeling
|
| 20 |
+
from datasets import load_dataset, DatasetDict, Dataset
|
| 21 |
+
import pandas as pd
|
| 22 |
+
from torch.utils.data import Dataset as TorchDataset, DataLoader, random_split
|
| 23 |
+
from sklearn.model_selection import train_test_split
|
| 24 |
+
from ranger21 import Ranger21
|
| 25 |
+
from tqdm.notebook import tqdm
|
| 26 |
+
from FastChemTokenizerHF import FastChemTokenizerSelfies
|
| 27 |
+
from ChemQ3MTP import ChemQ3MTPConfig, ChemQ3MTPForCausalLM # This should now work
|
| 28 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 29 |
+
from transformers import TrainerCallback
|
| 30 |
+
import datetime
|
| 31 |
+
|
| 32 |
+
# Clear cache functions
|
| 33 |
+
def clear_cache():
|
| 34 |
+
"""Clear PyTorch and CUDA caches"""
|
| 35 |
+
print("Clearing PyTorch and CUDA caches...")
|
| 36 |
+
if torch.cuda.is_available():
|
| 37 |
+
torch.cuda.empty_cache()
|
| 38 |
+
torch.cuda.synchronize()
|
| 39 |
+
print("CUDA cache cleared")
|
| 40 |
+
torch.backends.cudnn.benchmark = True # Enable cuDNN optimization
|
| 41 |
+
print("PyTorch cache cleared")
|
| 42 |
+
|
| 43 |
+
def clear_datasets_cache():
|
| 44 |
+
"""Clear datasets cache directory"""
|
| 45 |
+
import shutil
|
| 46 |
+
from datasets import disable_caching, enable_caching, get_cache_directory
|
| 47 |
+
try:
|
| 48 |
+
cache_dir = get_cache_directory()
|
| 49 |
+
print(f"Clearing datasets cache at: {cache_dir}")
|
| 50 |
+
if os.path.exists(cache_dir):
|
| 51 |
+
shutil.rmtree(cache_dir)
|
| 52 |
+
print("Datasets cache cleared")
|
| 53 |
+
except:
|
| 54 |
+
print("Could not clear datasets cache (may not exist)")
|
| 55 |
+
|
| 56 |
+
# ==============================
|
| 57 |
+
# Clear caches before starting
|
| 58 |
+
# ==============================
|
| 59 |
+
clear_cache()
|
| 60 |
+
# clear_datasets_cache()
|
| 61 |
+
|
| 62 |
+
# ==============================
|
| 63 |
+
# Load external configuration
|
| 64 |
+
# ==============================
|
| 65 |
+
with open("config.json", "r") as f:
|
| 66 |
+
CONFIG = json.load(f)
|
| 67 |
+
|
| 68 |
+
TRAINING_CFG = CONFIG["training"]
|
| 69 |
+
MODEL_CFG = {k: v for k, v in CONFIG.items()
|
| 70 |
+
if k not in ["training", "generation", "model_type", "architectures"]}
|
| 71 |
+
GENERATION_CFG = CONFIG.get("generation", {})
|
| 72 |
+
|
| 73 |
+
# Training params
|
| 74 |
+
BATCH_SIZE = TRAINING_CFG["batch_size"]
|
| 75 |
+
NUM_EPOCHS = TRAINING_CFG["num_epochs"]
|
| 76 |
+
LEARNING_RATE = TRAINING_CFG["learning_rate"]
|
| 77 |
+
WEIGHT_DECAY = TRAINING_CFG["weight_decay"]
|
| 78 |
+
GRAD_ACCUM_STEPS = TRAINING_CFG["gradient_accumulation_steps"]
|
| 79 |
+
TOKENIZE_BATCH_SIZE = TRAINING_CFG["tokenize_batch_size"]
|
| 80 |
+
TRAIN_SPLIT_RATIO = TRAINING_CFG["train_split_ratio"]
|
| 81 |
+
VAL_SPLIT_RATIO = TRAINING_CFG["val_split_ratio"]
|
| 82 |
+
TEST_SPLIT_RATIO = TRAINING_CFG["test_split_ratio"]
|
| 83 |
+
INCLUDE_FOR_METRICS = TRAINING_CFG.get("include_for_metrics", ["input_ids", "attention_mask", "labels"])
|
| 84 |
+
# ==============================
|
| 85 |
+
|
| 86 |
+
class LossLoggerCallback(TrainerCallback):
|
| 87 |
+
def __init__(self, log_file="training_losses.txt", with_timestamp=False):
|
| 88 |
+
self.log_file = log_file
|
| 89 |
+
self.with_timestamp = with_timestamp
|
| 90 |
+
with open(self.log_file, "w") as f:
|
| 91 |
+
if self.with_timestamp:
|
| 92 |
+
f.write("time\tstep\tloss\teval_loss\n")
|
| 93 |
+
else:
|
| 94 |
+
f.write("step\tloss\teval_loss\n")
|
| 95 |
+
|
| 96 |
+
def on_log(self, args, state, control, logs=None, **kwargs):
|
| 97 |
+
if logs is None:
|
| 98 |
+
return
|
| 99 |
+
step = state.global_step
|
| 100 |
+
loss = logs.get("loss")
|
| 101 |
+
eval_loss = logs.get("eval_loss")
|
| 102 |
+
|
| 103 |
+
with open(self.log_file, "a") as f:
|
| 104 |
+
if self.with_timestamp:
|
| 105 |
+
ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 106 |
+
f.write(f"{ts}\t{step}\t{loss if loss is not None else ''}\t{eval_loss if eval_loss is not None else ''}\n")
|
| 107 |
+
else:
|
| 108 |
+
f.write(f"{step}\t{loss if loss is not None else ''}\t{eval_loss if eval_loss is not None else ''}\n")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class CheckpointEvery10PercentCallback(TrainerCallback):
|
| 112 |
+
"""
|
| 113 |
+
Custom callback to save checkpoints at 10% intervals of total training progress
|
| 114 |
+
"""
|
| 115 |
+
def __init__(self, save_dir, total_steps):
|
| 116 |
+
self.save_dir = save_dir
|
| 117 |
+
self.total_steps = total_steps
|
| 118 |
+
self.checkpoint_intervals = []
|
| 119 |
+
# Calculate steps for 10% intervals (10%, 20%, 30%, ..., 100%)
|
| 120 |
+
for i in range(1, 11):
|
| 121 |
+
checkpoint_step = int(total_steps * i * 0.1)
|
| 122 |
+
self.checkpoint_intervals.append(checkpoint_step)
|
| 123 |
+
self.saved_checkpoints = set()
|
| 124 |
+
print(f"Checkpoint intervals: {self.checkpoint_intervals}")
|
| 125 |
+
|
| 126 |
+
def on_step_end(self, args, state, control, **kwargs):
|
| 127 |
+
current_step = state.global_step
|
| 128 |
+
|
| 129 |
+
# Check if we've reached a 10% checkpoint
|
| 130 |
+
for checkpoint_step in self.checkpoint_intervals:
|
| 131 |
+
if current_step == checkpoint_step and checkpoint_step not in self.saved_checkpoints:
|
| 132 |
+
checkpoint_dir = f"{self.save_dir}/checkpoint_10percent_{current_step}"
|
| 133 |
+
print(f"Saving 10% progress checkpoint at step {current_step} to {checkpoint_dir}")
|
| 134 |
+
|
| 135 |
+
# Save model and tokenizer
|
| 136 |
+
model = kwargs.get('model')
|
| 137 |
+
tokenizer = kwargs.get('processing_class') # or kwargs.get('tokenizer')
|
| 138 |
+
|
| 139 |
+
if model is not None:
|
| 140 |
+
model.save_pretrained(checkpoint_dir)
|
| 141 |
+
if tokenizer is not None:
|
| 142 |
+
tokenizer.save_pretrained(checkpoint_dir)
|
| 143 |
+
|
| 144 |
+
# Also save training state
|
| 145 |
+
if hasattr(kwargs.get('trainer'), 'save_state'):
|
| 146 |
+
kwargs['trainer'].save_state()
|
| 147 |
+
|
| 148 |
+
self.saved_checkpoints.add(checkpoint_step)
|
| 149 |
+
print(f"Checkpoint saved at step {current_step} ({current_step/self.total_steps*100:.1f}% completion)")
|
| 150 |
+
break # Only save one checkpoint per step
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def tokenize_function(examples, tokenizer, max_length):
|
| 154 |
+
"""Tokenize function defined outside main to avoid closure issues"""
|
| 155 |
+
batch_results = {"input_ids": [], "attention_mask": [], "labels": []}
|
| 156 |
+
smiles_list = examples['SELFIES'] if isinstance(examples['SELFIES'], list) else [examples['SELFIES']]
|
| 157 |
+
for smiles in smiles_list:
|
| 158 |
+
tokenized = tokenizer(
|
| 159 |
+
smiles,
|
| 160 |
+
truncation=True,
|
| 161 |
+
padding=False,
|
| 162 |
+
max_length=max_length,
|
| 163 |
+
return_tensors=None,
|
| 164 |
+
add_special_tokens=True
|
| 165 |
+
)
|
| 166 |
+
input_ids = tokenized["input_ids"]
|
| 167 |
+
attention_mask = tokenized["attention_mask"]
|
| 168 |
+
labels = input_ids.copy()
|
| 169 |
+
batch_results["input_ids"].append(input_ids)
|
| 170 |
+
batch_results["attention_mask"].append(attention_mask)
|
| 171 |
+
batch_results["labels"].append(labels)
|
| 172 |
+
return batch_results
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def main():
|
| 176 |
+
# Clear cache at the beginning of main function too
|
| 177 |
+
clear_cache()
|
| 178 |
+
|
| 179 |
+
# --- Load the tokenizer ---
|
| 180 |
+
tokenizer = FastChemTokenizerSelfies.from_pretrained("../selftok_core")
|
| 181 |
+
|
| 182 |
+
out = tokenizer("[C] [=C] [Branch1]", return_tensors="pt")
|
| 183 |
+
print(out.input_ids)
|
| 184 |
+
print(out.attention_mask)
|
| 185 |
+
out = out.to("cuda" if torch.cuda.is_available() else "cpu")
|
| 186 |
+
print(out.input_ids.device)
|
| 187 |
+
|
| 188 |
+
checkpoint_path = "./chunk-2"
|
| 189 |
+
|
| 190 |
+
if os.path.isdir(checkpoint_path):
|
| 191 |
+
print(f"Loading model from checkpoint: {checkpoint_path}")
|
| 192 |
+
model = ChemQ3MTPForCausalLM.from_pretrained(checkpoint_path)
|
| 193 |
+
config = model.config
|
| 194 |
+
else:
|
| 195 |
+
print("No checkpoint found, initializing new model.")
|
| 196 |
+
config = ChemQ3MTPConfig(
|
| 197 |
+
vocab_size=len(tokenizer),
|
| 198 |
+
bos_token_id=tokenizer.bos_token_id,
|
| 199 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 200 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 201 |
+
**MODEL_CFG
|
| 202 |
+
)
|
| 203 |
+
model = ChemQ3MTPForCausalLM(config)
|
| 204 |
+
|
| 205 |
+
def count_parameters(model):
|
| 206 |
+
return sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 207 |
+
|
| 208 |
+
print(f"Enhanced model has {count_parameters(model):,} trainable parameters.")
|
| 209 |
+
|
| 210 |
+
batch_size, seq_len = 2, 32
|
| 211 |
+
dummy_input = torch.randint(
|
| 212 |
+
low=0,
|
| 213 |
+
high=len(tokenizer),
|
| 214 |
+
size=(batch_size, seq_len),
|
| 215 |
+
dtype=torch.long,
|
| 216 |
+
)
|
| 217 |
+
with torch.no_grad():
|
| 218 |
+
outputs = model(dummy_input)
|
| 219 |
+
logits = outputs.logits
|
| 220 |
+
print(f"Input shape: {dummy_input.shape}")
|
| 221 |
+
print(f"Logits shape: {logits.shape}")
|
| 222 |
+
|
| 223 |
+
print("Loading dataset...")
|
| 224 |
+
# Load dataset without streaming
|
| 225 |
+
dataset = load_dataset(
|
| 226 |
+
'csv',
|
| 227 |
+
data_files='../data/chunk_3.csv',
|
| 228 |
+
split='train'
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
print(f"Dataset loaded with {len(dataset)} samples")
|
| 232 |
+
|
| 233 |
+
# Verify the correct file is loaded by checking first few samples
|
| 234 |
+
print("First few samples from dataset:")
|
| 235 |
+
for i in range(min(3, len(dataset))):
|
| 236 |
+
sample = dataset[i]
|
| 237 |
+
print(f"Sample {i}: {sample}")
|
| 238 |
+
if 'SELFIES' in sample:
|
| 239 |
+
print(f"First SELFIES: {sample['SELFIES']}")
|
| 240 |
+
break
|
| 241 |
+
|
| 242 |
+
print("Shuffling and splitting dataset...")
|
| 243 |
+
# Shuffle the entire dataset first
|
| 244 |
+
dataset = dataset.shuffle(seed=42)
|
| 245 |
+
|
| 246 |
+
# Calculate split sizes
|
| 247 |
+
total_lines = len(dataset)
|
| 248 |
+
test_size = int(TEST_SPLIT_RATIO * total_lines)
|
| 249 |
+
val_size = int(VAL_SPLIT_RATIO * total_lines)
|
| 250 |
+
train_size = total_lines - test_size - val_size
|
| 251 |
+
|
| 252 |
+
print(f"Total samples: {total_lines}")
|
| 253 |
+
print(f"Split sizes - train: {train_size}, val: {val_size}, test: {test_size}")
|
| 254 |
+
|
| 255 |
+
# Create splits using select
|
| 256 |
+
train_dataset = dataset.select(range(0, train_size))
|
| 257 |
+
val_dataset = dataset.select(range(train_size, train_size + val_size))
|
| 258 |
+
test_dataset = dataset.select(range(train_size + val_size, total_lines))
|
| 259 |
+
|
| 260 |
+
print(f"Dataset split: train={len(train_dataset)}, val={len(val_dataset)}, test={len(test_dataset)}")
|
| 261 |
+
|
| 262 |
+
# Tokenize datasets using batched mapping with explicit parameters
|
| 263 |
+
print("Tokenizing datasets...")
|
| 264 |
+
|
| 265 |
+
# Define tokenize function with all parameters passed explicitly
|
| 266 |
+
def tokenize_train(examples):
|
| 267 |
+
return tokenize_function(examples, tokenizer, MODEL_CFG["max_position_embeddings"])
|
| 268 |
+
|
| 269 |
+
def tokenize_val(examples):
|
| 270 |
+
return tokenize_function(examples, tokenizer, MODEL_CFG["max_position_embeddings"])
|
| 271 |
+
|
| 272 |
+
train_dataset = train_dataset.map(
|
| 273 |
+
tokenize_train,
|
| 274 |
+
batched=True,
|
| 275 |
+
batch_size=TOKENIZE_BATCH_SIZE,
|
| 276 |
+
remove_columns=["SELFIES"],
|
| 277 |
+
desc="Tokenizing train dataset"
|
| 278 |
+
)
|
| 279 |
+
val_dataset = val_dataset.map(
|
| 280 |
+
tokenize_val,
|
| 281 |
+
batched=True,
|
| 282 |
+
batch_size=TOKENIZE_BATCH_SIZE,
|
| 283 |
+
remove_columns=["SELFIES"],
|
| 284 |
+
desc="Tokenizing val dataset"
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
class EnhancedDataCollator:
|
| 288 |
+
def __init__(self, tokenizer, pad_to_multiple_of=8):
|
| 289 |
+
self.tokenizer = tokenizer
|
| 290 |
+
self.pad_to_multiple_of = pad_to_multiple_of
|
| 291 |
+
def __call__(self, features):
|
| 292 |
+
max_length = max(len(f["input_ids"]) for f in features)
|
| 293 |
+
if self.pad_to_multiple_of:
|
| 294 |
+
max_length = ((max_length + self.pad_to_multiple_of - 1) // self.pad_to_multiple_of) * self.pad_to_multiple_of
|
| 295 |
+
batch = {"input_ids": [], "attention_mask": [], "labels": []}
|
| 296 |
+
for feature in features:
|
| 297 |
+
input_ids = feature["input_ids"]
|
| 298 |
+
attention_mask = feature["attention_mask"]
|
| 299 |
+
labels = feature["labels"]
|
| 300 |
+
padding_length = max_length - len(input_ids)
|
| 301 |
+
padded_input_ids = input_ids + [self.tokenizer.pad_token_id] * padding_length
|
| 302 |
+
padded_attention_mask = attention_mask + [0] * padding_length
|
| 303 |
+
padded_labels = labels + [-100] * padding_length
|
| 304 |
+
batch["input_ids"].append(padded_input_ids)
|
| 305 |
+
batch["attention_mask"].append(padded_attention_mask)
|
| 306 |
+
batch["labels"].append(padded_labels)
|
| 307 |
+
batch = {key: torch.tensor(values, dtype=torch.long) for key, values in batch.items()}
|
| 308 |
+
return batch
|
| 309 |
+
|
| 310 |
+
data_collator = EnhancedDataCollator(tokenizer, pad_to_multiple_of=8)
|
| 311 |
+
|
| 312 |
+
def create_enhanced_optimizer(model_params):
|
| 313 |
+
num_batches_per_epoch = len(train_dataset) // BATCH_SIZE
|
| 314 |
+
optimizer_params = {
|
| 315 |
+
'lr': LEARNING_RATE,
|
| 316 |
+
'weight_decay': WEIGHT_DECAY,
|
| 317 |
+
'use_adabelief': True,
|
| 318 |
+
'use_cheb': False,
|
| 319 |
+
'use_warmup': True,
|
| 320 |
+
'use_madgrad': True,
|
| 321 |
+
'num_epochs': NUM_EPOCHS,
|
| 322 |
+
'using_gc': True,
|
| 323 |
+
'warmdown_active': True,
|
| 324 |
+
'num_batches_per_epoch': num_batches_per_epoch
|
| 325 |
+
}
|
| 326 |
+
return Ranger21(model_params, **optimizer_params)
|
| 327 |
+
|
| 328 |
+
from torch.optim.lr_scheduler import LambdaLR
|
| 329 |
+
class EnhancedCustomTrainer(Trainer):
|
| 330 |
+
def create_optimizer(self):
|
| 331 |
+
self.optimizer = create_enhanced_optimizer(self.model.parameters())
|
| 332 |
+
return self.optimizer
|
| 333 |
+
def create_scheduler(self, num_training_steps, optimizer=None):
|
| 334 |
+
if optimizer is None:
|
| 335 |
+
optimizer = self.optimizer
|
| 336 |
+
self.lr_scheduler = LambdaLR(optimizer, lr_lambda=lambda step: 1.0)
|
| 337 |
+
return self.lr_scheduler
|
| 338 |
+
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
|
| 339 |
+
outputs = model(**inputs)
|
| 340 |
+
loss = outputs.loss
|
| 341 |
+
return (loss, outputs) if return_outputs else loss
|
| 342 |
+
|
| 343 |
+
steps_per_epoch = len(train_dataset) // BATCH_SIZE
|
| 344 |
+
total_steps = steps_per_epoch * NUM_EPOCHS
|
| 345 |
+
|
| 346 |
+
training_args = TrainingArguments(
|
| 347 |
+
output_dir='./chemq3minipret',
|
| 348 |
+
max_steps=total_steps,
|
| 349 |
+
per_device_train_batch_size=BATCH_SIZE,
|
| 350 |
+
per_device_eval_batch_size=BATCH_SIZE,
|
| 351 |
+
gradient_accumulation_steps=GRAD_ACCUM_STEPS,
|
| 352 |
+
logging_dir='./gptlo-1',
|
| 353 |
+
logging_strategy="steps",
|
| 354 |
+
logging_steps=max(1, steps_per_epoch // 4),
|
| 355 |
+
eval_strategy="steps",
|
| 356 |
+
eval_steps=max(1, steps_per_epoch // 4),
|
| 357 |
+
save_strategy="steps",
|
| 358 |
+
save_steps=steps_per_epoch, # Save every epoch
|
| 359 |
+
save_total_limit=1,
|
| 360 |
+
dataloader_num_workers=0,
|
| 361 |
+
dataloader_pin_memory=False,
|
| 362 |
+
remove_unused_columns=False,
|
| 363 |
+
prediction_loss_only=False,
|
| 364 |
+
fp16=torch.cuda.is_available(),
|
| 365 |
+
gradient_checkpointing=True,
|
| 366 |
+
dataloader_drop_last=True,
|
| 367 |
+
report_to=None,
|
| 368 |
+
include_for_metrics=INCLUDE_FOR_METRICS,
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
print("Initializing enhanced trainer with MTP capabilities...")
|
| 372 |
+
trainer = EnhancedCustomTrainer(
|
| 373 |
+
model=model,
|
| 374 |
+
args=training_args,
|
| 375 |
+
train_dataset=train_dataset,
|
| 376 |
+
eval_dataset=val_dataset,
|
| 377 |
+
data_collator=data_collator,
|
| 378 |
+
processing_class=tokenizer,
|
| 379 |
+
callbacks=[
|
| 380 |
+
LossLoggerCallback("training_losses.txt", with_timestamp=True),
|
| 381 |
+
CheckpointEvery10PercentCallback("./chemq3minipret", total_steps)
|
| 382 |
+
]
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
model.set_mtp_training(True)
|
| 386 |
+
print(" MTP training mode enabled")
|
| 387 |
+
|
| 388 |
+
print("Starting enhanced training with MTP and Horizon Loss...")
|
| 389 |
+
try:
|
| 390 |
+
print("\n Phase 1: Warmup with standard Causal LM...")
|
| 391 |
+
model.set_mtp_training(False)
|
| 392 |
+
warmup_steps = max(1, total_steps // 5)
|
| 393 |
+
|
| 394 |
+
# Update trainer args for warmup phase
|
| 395 |
+
trainer.args.max_steps = warmup_steps
|
| 396 |
+
trainer.train()
|
| 397 |
+
print(f"\n Phase 1 completed. Warmup with {warmup_steps} steps finished.")
|
| 398 |
+
|
| 399 |
+
print(f"\n Phase 2: Full MTP + Horizon Loss training...")
|
| 400 |
+
print(f"Total training steps: {total_steps}")
|
| 401 |
+
print(f"Training will save checkpoints at 10% intervals:")
|
| 402 |
+
for i in range(1, 11):
|
| 403 |
+
checkpoint_step = int(total_steps * i * 0.1)
|
| 404 |
+
print(f" - {i*10}%: Step {checkpoint_step}")
|
| 405 |
+
|
| 406 |
+
model.set_mtp_training(True)
|
| 407 |
+
# Reset max steps to total for the full training phase
|
| 408 |
+
trainer.args.max_steps = total_steps
|
| 409 |
+
trainer.train(resume_from_checkpoint=True)
|
| 410 |
+
print("Enhanced training completed successfully!")
|
| 411 |
+
trainer.save_model("./enhanced-qwen3-final")
|
| 412 |
+
tokenizer.save_pretrained("./enhanced-qwen3-final")
|
| 413 |
+
training_config = {
|
| 414 |
+
"model_type": "ChemQ3MTPForCausalLM",
|
| 415 |
+
"num_future_tokens": 3,
|
| 416 |
+
"horizon_loss_enabled": True,
|
| 417 |
+
"mtp_head_enabled": True,
|
| 418 |
+
"training_phases": ["causal_lm_warmup", "mtp_horizon_training"],
|
| 419 |
+
"total_parameters": count_parameters(model),
|
| 420 |
+
}
|
| 421 |
+
config_path = "./enhanced-qwen3-final/training_config.json"
|
| 422 |
+
with open(config_path, "w") as f:
|
| 423 |
+
json.dump(training_config, f, indent=2)
|
| 424 |
+
print(f" Enhanced model, tokenizer, and config saved!")
|
| 425 |
+
except Exception as e:
|
| 426 |
+
print(f"Enhanced training failed with error: {e}")
|
| 427 |
+
import traceback
|
| 428 |
+
traceback.print_exc()
|
| 429 |
+
return
|
| 430 |
+
|
| 431 |
+
print("\nmTesting enhanced generation capabilities...")
|
| 432 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 433 |
+
model.to(device)
|
| 434 |
+
model.eval()
|
| 435 |
+
try:
|
| 436 |
+
print("\n--- Standard Generation Test ---")
|
| 437 |
+
input_ids = tokenizer("<s> [C]", return_tensors="pt").input_ids.to(device)
|
| 438 |
+
with torch.no_grad():
|
| 439 |
+
model.set_mtp_training(False)
|
| 440 |
+
gen = model.generate(
|
| 441 |
+
input_ids,
|
| 442 |
+
max_length=25,
|
| 443 |
+
top_k=50,
|
| 444 |
+
top_p=0.9,
|
| 445 |
+
temperature=1.0,
|
| 446 |
+
do_sample=True,
|
| 447 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 448 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 449 |
+
num_return_sequences=3,
|
| 450 |
+
)
|
| 451 |
+
for i, sequence in enumerate(gen):
|
| 452 |
+
result = tokenizer.decode(sequence, skip_special_tokens=True)
|
| 453 |
+
print(f"Generated SELFIES {i+1}: {result}")
|
| 454 |
+
print("\n--- MTP Analysis Test ---")
|
| 455 |
+
test_smiles = "[C]"
|
| 456 |
+
test_input = tokenizer(test_smiles, return_tensors="pt", add_special_tokens=True).to(device)
|
| 457 |
+
test_input = {k: v for k, v in test_input.items() if k != 'token_type_ids'} # Remove token_type_ids
|
| 458 |
+
with torch.no_grad():
|
| 459 |
+
outputs = model(**test_input)
|
| 460 |
+
if hasattr(model, 'mtp_head') and hasattr(model.mtp_head, 'prediction_heads'):
|
| 461 |
+
hidden_states = model.model(test_input['input_ids']).last_hidden_state
|
| 462 |
+
mtp_outputs = model.mtp_head(hidden_states)
|
| 463 |
+
print(f"Input SELFIES: {test_smiles}")
|
| 464 |
+
print(f"Tokenized: {tokenizer.convert_ids_to_tokens(test_input['input_ids'][0].tolist())}")
|
| 465 |
+
for i, (key, logits) in enumerate(mtp_outputs.items()):
|
| 466 |
+
top_tokens = torch.topk(logits[0], k=3, dim=-1)
|
| 467 |
+
print(f"\n{key} predictions:")
|
| 468 |
+
for pos in range(min(5, logits.size(1))):
|
| 469 |
+
pos_preds = []
|
| 470 |
+
for j in range(3):
|
| 471 |
+
token_id = top_tokens.indices[pos, j].item()
|
| 472 |
+
prob = torch.softmax(logits[0, pos], dim=-1)[token_id].item()
|
| 473 |
+
token = tokenizer.id_to_token.get(token_id, '<UNK>')
|
| 474 |
+
pos_preds.append(f"{token}({prob:.3f})")
|
| 475 |
+
print(f" Position {pos}: {', '.join(pos_preds)}")
|
| 476 |
+
print("\nEnhanced generation tests completed!")
|
| 477 |
+
except Exception as e:
|
| 478 |
+
print(f"Enhanced generation test failed: {e}")
|
| 479 |
+
import traceback
|
| 480 |
+
traceback.print_exc()
|
| 481 |
+
|
| 482 |
+
print("\nEnhanced Model Analysis:")
|
| 483 |
+
print(f"Total parameters: {count_parameters(model):,}")
|
| 484 |
+
mtp_params = sum(p.numel() for p in model.mtp_head.parameters() if p.requires_grad)
|
| 485 |
+
horizon_params = sum(p.numel() for p in model.horizon_loss.parameters() if p.requires_grad)
|
| 486 |
+
base_params = count_parameters(model) - mtp_params - horizon_params
|
| 487 |
+
print(f"Base model parameters: {base_params:,}")
|
| 488 |
+
print(f"MTP head parameters: {mtp_params:,}")
|
| 489 |
+
print(f"Horizon loss parameters: {horizon_params:,}")
|
| 490 |
+
print(f"Enhancement overhead: {((mtp_params + horizon_params) / base_params * 100):.2f}%")
|
| 491 |
+
print(f"\n Enhanced Model Architecture:")
|
| 492 |
+
print(f"- Base Model: Qwen2 with {config.num_hidden_layers} layers") # Updated this line
|
| 493 |
+
print(f"- Hidden Size: {config.hidden_size}")
|
| 494 |
+
print(f"- Attention Heads: {config.num_attention_heads}")
|
| 495 |
+
print(f"- Vocab Size: {config.vocab_size}")
|
| 496 |
+
print(f"- MTP Future Tokens: {model.mtp_head.num_future_tokens}")
|
| 497 |
+
print(f"- Horizon Loss Weights: Learnable")
|
| 498 |
+
print(f"- Training Mode: {'MTP + Horizon Loss' if model.use_mtp_training else 'Standard Causal LM'}")
|
| 499 |
+
print("\n Enhanced training pipeline completed successfully!")
|
| 500 |
+
|
| 501 |
+
if __name__ == "__main__":
|
| 502 |
+
main()
|