File size: 14,479 Bytes
74b7543 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 | import torch
import wandb
import os
import json
import numpy as np
from itertools import chain
from transformers import GPT2Config, GPTJConfig, GPTJForCausalLM, GPT2Model, GPT2TokenizerFast, GPT2Tokenizer, Trainer, TrainingArguments, AddedToken
from transformers import AutoModelForCausalLM
from transformers import default_data_collator, DataCollatorForLanguageModeling
from transformers.optimization import AdamW, get_scheduler, get_cosine_with_min_lr_schedule_with_warmup, get_constant_schedule_with_warmup
from transformers.trainer_utils import get_last_checkpoint
from datasets import load_dataset
from utils.data.name_space import single_names
from utils.training.collator.collator import DynamicCollator
def resolve_attn_implementation(config: dict) -> str:
attn_impl = config.get("attn_implementation", "flash_attention_2")
if attn_impl == "flash_attention_2":
if not torch.cuda.is_available():
print("FlashAttention2 requested but CUDA is unavailable; falling back to eager attention.")
return "eager"
try:
import flash_attn # noqa: F401
except Exception as exc:
print(f"flash-attn unavailable ({exc}); falling back to eager.")
return "eager"
if attn_impl == "sdpa":
print("GPT-J does not support SDPA; falling back to eager.")
return "eager"
return attn_impl
# Define GPT-J configuration using GPT-2's default hyperparameters
def create_gptj_config_from_gpt2_defaults():
gpt2_config = GPT2Config()
gptj_config = GPTJConfig(
vocab_size=gpt2_config.vocab_size,
n_positions=gpt2_config.n_positions,
n_embd=gpt2_config.n_embd // 2,
n_layer=gpt2_config.n_layer // 2,
n_head=gpt2_config.n_head // 2,
activation_function=gpt2_config.activation_function,
resid_pdrop=gpt2_config.resid_pdrop,
embd_pdrop=gpt2_config.embd_pdrop,
attn_pdrop=gpt2_config.attn_pdrop,
layer_norm_epsilon=gpt2_config.layer_norm_epsilon,
# rotary_dim=64,
)
return gptj_config
def train(config_path: str):
# Initialize distributed process group early if running with torchrun
if "RANK" in os.environ and "WORLD_SIZE" in os.environ:
if not torch.distributed.is_initialized():
torch.distributed.init_process_group(backend="nccl")
# Load configuration from JSON file
with open(config_path, "r") as f:
config = json.load(f)
# Use explicit output_dir from config if available
if config.get("output_dir"):
output_dir = config["output_dir"]
else:
# Construct output directory based on graph parameters
num_e = config.get("num_entities", "X")
num_r = config.get("num_relations", "X")
k = config.get("num_hops", "X")
d = config.get("edges_per_entity", "X")
# Distribution info for naming
alpha = config.get("sampling_alpha")
if alpha is not None:
dist_str = f"powerlaw_a{alpha}"
else:
dist_str = "uniform"
# Use the config filename as the experiment identifier
exp_id = os.path.basename(config_path).replace('.json', '')
output_dir = f"archives/E{num_e}_R{num_r}_k{k}_D{d}_{dist_str}/{exp_id}"
os.makedirs(output_dir, exist_ok=True)
# Initialize tokenizer (GPT-2 Tokenizer, compatible with GPT-J)
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
tokenizer.pad_token = tokenizer.eos_token
if config.get("add_tokens", False):
names = single_names
tokenizer.add_tokens(names)
tokenizer.save_pretrained(output_dir)
use_wandb = bool(config.get("use_wandb", False))
if use_wandb:
# set the wandb project where this run will be logged
os.environ["WANDB_PROJECT"] = "lm_implicit_multihop_reasoning"
# save your trained model checkpoint to wandb
os.environ["WANDB_LOG_MODEL"] = "false"
# turn off watch to log faster
os.environ["WANDB_WATCH"] = "True"
else:
os.environ["WANDB_DISABLED"] = "true"
# Set up training arguments
num_gpus = torch.cuda.device_count()
grad_acc_steps = config.get("gradient_accumulation_steps", 1)
if grad_acc_steps < 1:
print(f"Warning: gradient_accumulation_steps was {grad_acc_steps}, setting to 1.")
grad_acc_steps = 1
training_args = TrainingArguments(
output_dir=output_dir,
per_device_train_batch_size=config.get("per_device_train_batch_size", 8),
gradient_accumulation_steps=grad_acc_steps,
num_train_epochs=config.get("num_train_epochs", 1),
max_steps=config.get("max_steps", -1),
learning_rate=config.get("learning_rate", 5e-5),
warmup_steps=config.get("warmup_steps", 0),
logging_dir=config.get("logging_dir", f"{output_dir}/logs"),
logging_steps=config.get("logging_steps", 10),
save_steps=config.get("save_steps", 500),
save_total_limit=config.get("save_total_limit", 2),
weight_decay=config.get("weight_decay", 0.1),
lr_scheduler_type=config.get("lr_scheduler_type", "cosine"),
report_to="wandb" if use_wandb else "none",
dataloader_num_workers=4,
ddp_find_unused_parameters=False,
seed=config.get("seed", 42),
)
model_type = config.get("model_type", "gptj")
attn_impl = resolve_attn_implementation(config)
if not config.get("pretrain_ckpt"):
gptj_config = create_gptj_config_from_gpt2_defaults()
gptj_config._attn_implementation = attn_impl
if model_type == "gptj":
model = GPTJForCausalLM(config=gptj_config)
else:
raise ValueError(f"Unknown model type: {model_type}")
else:
print(f"Loading model from {config['pretrain_ckpt']}")
if model_type == "gptj":
model = GPTJForCausalLM.from_pretrained(
config["pretrain_ckpt"],
attn_implementation=attn_impl,
)
else:
model = AutoModelForCausalLM.from_pretrained(
config["pretrain_ckpt"])
embedding_size = model.get_input_embeddings().weight.shape[0]
if len(tokenizer) > embedding_size:
model.resize_token_embeddings(len(tokenizer))
if config.get("torch_compile", False):
print("Compiling model with torch.compile...")
model = torch.compile(model)
# Initialize the AdamW optimizer
optimizer = AdamW(model.parameters(), lr=training_args.learning_rate, eps=1e-6, weight_decay=config.get("weight_decay", 0.1))
# Prepare a dataset
if config.get("online_data", False):
print("Using Online Data Generation...")
from online_data import OnlineDataset
from generate_data import DataGenerator
generator = DataGenerator(
num_entities=config.get("num_entities", 50),
num_relations=config.get("num_relations", 50),
seed=config.get("seed", 42),
sampling_alpha=config.get("sampling_alpha", None)
)
print("Generating Graph for Online Data...")
generator.generate_graph(edges_per_entity=config.get("edges_per_entity", 10))
tokenized_datasets = OnlineDataset(
generator=generator,
num_hops=config.get("num_hops", 2),
train_qa_ratio=config.get("train_qa_ratio", 0.5),
tokenizer=tokenizer,
max_length=config.get("max_length", 100),
padding=config.get("padding", False)
)
print("Online Dataset Ready.")
# Generate a test set specifically for THIS graph and save it in the model folder
# Only do this on rank 0 to avoid race conditions
rank = 0
if torch.distributed.is_initialized():
rank = torch.distributed.get_rank()
if rank == 0:
print("Generating graph-consistent test set for evaluation (4096 examples)...")
# 1. Native test set (matches training distribution)
test_examples = generator.generate_test_examples(num_examples=4096, num_hops=config.get("num_hops", 2))
test_save_path = os.path.join(output_dir, "eval_test.json")
with open(test_save_path, "w") as f:
json.dump(test_examples, f, indent=2)
print(f"Saved native test set to {test_save_path}")
# 2. Uniform test set (fair comparison across experiments)
if generator.sampling_alpha is not None:
print("Generating uniform test set for fair comparison...")
orig_alpha = generator.sampling_alpha
generator.sampling_alpha = None # Temporarily disable power law
test_examples_uniform = generator.generate_test_examples(num_examples=4096, num_hops=config.get("num_hops", 2))
generator.sampling_alpha = orig_alpha # Restore
test_save_path_uniform = os.path.join(output_dir, "eval_test_uniform.json")
with open(test_save_path_uniform, "w") as f:
json.dump(test_examples_uniform, f, indent=2)
print(f"Saved uniform test set to {test_save_path_uniform}")
else:
# If training is already uniform, eval_test is already uniform.
# Create a symlink or copy for consistency in scripts
test_save_path_uniform = os.path.join(output_dir, "eval_test_uniform.json")
with open(test_save_path_uniform, "w") as f:
json.dump(test_examples, f, indent=2)
print(f"Saved uniform test set (identical to native) to {test_save_path_uniform}")
if torch.distributed.is_initialized():
torch.distributed.barrier() # Wait for rank 0 to finish saving
else:
def tokenize_function(examples):
# tokenize and add EOS token
# tokenized = tokenizer(examples["text"], padding="max_length", truncation=True, max_length=100)
tokenized = tokenizer(examples["text"], padding="max_length" if config.get("padding", False) else False,
truncation=True, max_length=config.get("max_length", 100), return_special_tokens_mask=True)
# with packing, add eos token at the end of each example
if not config.get("padding", False):
eos_token_id = tokenizer.eos_token_id
for i in range(len(tokenized["input_ids"])):
tokenized["input_ids"][i].append(eos_token_id)
tokenized["attention_mask"][i].append(
1)
# without packing, the labels are the same as input_ids
if config.get("padding", False):
tokenized["labels"] = tokenized["input_ids"].copy()
return tokenized
dataset = load_dataset("json", data_files=config["training_data"])
dataset = dataset["train"]
tokenized_datasets = dataset.map(tokenize_function, batched=True, remove_columns=["text"])
if config.get("padding", False):
tokenized_datasets.set_format("torch", columns=["input_ids", "attention_mask", "labels"])
else:
tokenized_datasets.set_format("torch", columns=["input_ids", "attention_mask"])
# print examples
print(f"Generated {len(tokenized_datasets)} examples")
# shuffle the dataset
tokenized_datasets = tokenized_datasets.shuffle(seed=config.get("seed", 42))
block_size = 512
if config.get("padding", False):
data_collator = default_data_collator
else:
data_collator = DynamicCollator(tokenizer, block_size)
if not config.get("online_data", False):
print(f"Training on {len(tokenized_datasets)} examples")
# Get total training steps
num_training_steps_cal = (
len(tokenized_datasets) // (training_args.per_device_train_batch_size * training_args.gradient_accumulation_steps)
) * training_args.num_train_epochs
else:
if training_args.max_steps == -1:
raise ValueError("For online data, max_steps must be specified in config.")
num_training_steps_cal = training_args.max_steps
per_device_accumulated_steps = training_args.gradient_accumulation_steps
per_device_accumulated_steps = training_args.gradient_accumulation_steps
num_training_steps = num_training_steps_cal if training_args.max_steps == -1 else training_args.max_steps
# Define the learning rate scheduler
print("Per device accumulated steps:", per_device_accumulated_steps)
print(f"Total training steps: {num_training_steps}")
if config.get("cosine_lr", True):
lr_scheduler = get_cosine_with_min_lr_schedule_with_warmup(
optimizer=optimizer, # Pass the optimizer instance
num_warmup_steps=training_args.warmup_steps,
num_training_steps=num_training_steps,
min_lr_rate=config.get("min_lr_rate", 0.1),
)
else:
lr_scheduler = get_constant_schedule_with_warmup(
optimizer=optimizer, num_warmup_steps=training_args.warmup_steps
)
# Initialize Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets,
optimizers=(optimizer, lr_scheduler), # Pass optimizer and scheduler
data_collator=data_collator,
processing_class=tokenizer,
)
# Train the model
last_ckpt = get_last_checkpoint(output_dir)
# Explicitly save the config to the output directory so checkpoints inherit it
model.config.save_pretrained(output_dir)
# if output_dir exists and contains a checkpoint, resume training from that checkpoint
if last_ckpt:
trainer.train(resume_from_checkpoint=True)
else:
trainer.train()
# Save the model
# If the model was compiled, save the original model to avoid "_orig_mod." prefix in weights
if hasattr(model, "_orig_mod"):
model._orig_mod.save_pretrained(output_dir)
else:
model.save_pretrained(output_dir)
if use_wandb:
wandb.finish()
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--config', type=str, required=True)
args = parser.parse_args()
train(args.config) # passing path to train function
|