Download code/multi-hop/train.py from fhyfhy/Implicit-Reasoning-checkpoints: direct link, hf CLI and curl.
- Browser
- Download file 14.5 kB
-
https://huggingface.co/fhyfhy/Implicit-Reasoning-checkpoints/resolve/main/code/multi-hop/train.py
- Command line
-
hf download hf://fhyfhy/Implicit-Reasoning-checkpoints/code/multi-hop/train.py
-
curl -L -o train.py https://huggingface.co/fhyfhy/Implicit-Reasoning-checkpoints/resolve/main/code/multi-hop/train.py
14.5 kB
| 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 | |