|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Standalone Constraint-Tracker LoRA Training Script for HF Jobs |
| 4 | +No repo cloning needed - everything is self-contained |
| 5 | +""" |
| 6 | + |
| 7 | +import json |
| 8 | +import os |
| 9 | +import gc |
| 10 | +import time |
| 11 | +import torch |
| 12 | +import traceback |
| 13 | +from pathlib import Path |
| 14 | +from huggingface_hub import hf_hub_download, snapshot_download, HfApi |
| 15 | +from datasets import Dataset |
| 16 | +from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig |
| 17 | +from peft import LoraConfig, get_peft_model, TaskType |
| 18 | + |
| 19 | +try: |
| 20 | + from trl import SFTTrainer, SFTConfig |
| 21 | + USE_NEW_TRL = True |
| 22 | +except ImportError: |
| 23 | + from trl import SFTTrainer |
| 24 | + from transformers import TrainingArguments |
| 25 | + USE_NEW_TRL = False |
| 26 | + |
| 27 | +# Configuration |
| 28 | +MODEL_NAME = "Raiff1982/codette-llama-3.1-8b-merged" |
| 29 | +DATASET_REPO = "Raiff1982/codette-training-data" |
| 30 | +OUTPUT_REPO = "Raiff1982/codette-lora-adapters" |
| 31 | +HF_TOKEN = os.environ.get("HF_TOKEN") |
| 32 | + |
| 33 | +ADAPTERS = [ |
| 34 | + ("constraint_tracker", "constraint_tracking.jsonl", 3), |
| 35 | +] |
| 36 | + |
| 37 | +LEARNING_RATE = 1e-4 |
| 38 | + |
| 39 | +print("=" * 60) |
| 40 | +print("Constraint-Tracker LoRA Training - Standalone") |
| 41 | +print("=" * 60) |
| 42 | +print(f"Base model: {MODEL_NAME}") |
| 43 | +print(f"Dataset repo: {DATASET_REPO}") |
| 44 | +print(f"Output repo: {OUTPUT_REPO}") |
| 45 | +print(f"HF Token present: {bool(HF_TOKEN)}") |
| 46 | +print(f"CUDA available: {torch.cuda.is_available()}") |
| 47 | + |
| 48 | +if torch.cuda.is_available(): |
| 49 | + print(f"GPU: {torch.cuda.get_device_name(0)}") |
| 50 | + print(f"VRAM: {torch.cuda.get_device_properties(0).total_memory/1024**3:.1f} GB") |
| 51 | + |
| 52 | +# Create output repo if needed |
| 53 | +api = HfApi(token=HF_TOKEN) |
| 54 | +try: |
| 55 | + api.create_repo(OUTPUT_REPO, private=True, token=HF_TOKEN) |
| 56 | + print(f"Output repo ready: {OUTPUT_REPO}") |
| 57 | +except: |
| 58 | + print(f"Output repo exists: {OUTPUT_REPO}") |
| 59 | + |
| 60 | +# Download dataset |
| 61 | +print("\nDownloading dataset...") |
| 62 | +dataset_dir = Path("/tmp/datasets") |
| 63 | +dataset_dir.mkdir(exist_ok=True) |
| 64 | + |
| 65 | +for adapter_name, dataset_file, _ in ADAPTERS: |
| 66 | + try: |
| 67 | + hf_hub_download(DATASET_REPO, dataset_file, repo_type="dataset", local_dir=str(dataset_dir)) |
| 68 | + print(f" Downloaded: {dataset_file}") |
| 69 | + except Exception as e: |
| 70 | + print(f" ERROR: Could not download {dataset_file}: {e}") |
| 71 | + raise |
| 72 | + |
| 73 | +# Load tokenizer |
| 74 | +print("\nLoading tokenizer...") |
| 75 | +tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=HF_TOKEN) |
| 76 | +if tokenizer.pad_token is None: |
| 77 | + tokenizer.pad_token = tokenizer.eos_token |
| 78 | + |
| 79 | +# Load model |
| 80 | +print(f"Loading model with QLoRA...") |
| 81 | +bnb_config = BitsAndBytesConfig( |
| 82 | + load_in_4bit=True, |
| 83 | + bnb_4bit_quant_type="nf4", |
| 84 | + bnb_4bit_compute_dtype=torch.bfloat16, |
| 85 | + bnb_4bit_use_double_quant=True, |
| 86 | +) |
| 87 | + |
| 88 | +model = AutoModelForCausalLM.from_pretrained( |
| 89 | + MODEL_NAME, |
| 90 | + quantization_config=bnb_config, |
| 91 | + device_map="auto", |
| 92 | + dtype=torch.bfloat16, |
| 93 | + trust_remote_code=True, |
| 94 | + use_cache=False, |
| 95 | + token=HF_TOKEN, |
| 96 | +) |
| 97 | +model.gradient_checkpointing_enable() |
| 98 | +print(f"Model loaded. GPU memory: {torch.cuda.memory_allocated()/1024**3:.2f} GB") |
| 99 | + |
| 100 | +# Training loop |
| 101 | +results = {} |
| 102 | +failed_uploads = [] |
| 103 | + |
| 104 | +for adapter_name, dataset_file, epochs in ADAPTERS: |
| 105 | + print(f"\n{'=' * 60}") |
| 106 | + print(f"Training: {adapter_name} ({epochs} epochs)") |
| 107 | + print(f"{'=' * 60}") |
| 108 | + |
| 109 | + start = time.time() |
| 110 | + |
| 111 | + # Load dataset |
| 112 | + dataset_path = dataset_dir / dataset_file |
| 113 | + if not dataset_path.exists(): |
| 114 | + print(f"ERROR: Dataset not found: {dataset_path}") |
| 115 | + raise FileNotFoundError(f"Dataset not found: {dataset_path}") |
| 116 | + |
| 117 | + examples = [] |
| 118 | + with open(dataset_path) as f: |
| 119 | + for line in f: |
| 120 | + line = line.strip() |
| 121 | + if line: |
| 122 | + examples.append(json.loads(line)) |
| 123 | + |
| 124 | + print(f" Loaded {len(examples)} examples") |
| 125 | + |
| 126 | + def format_example(ex): |
| 127 | + return {"text": tokenizer.apply_chat_template(ex["messages"], tokenize=False)} |
| 128 | + |
| 129 | + dataset = Dataset.from_list(examples).map(format_example, remove_columns=["messages"]) |
| 130 | + |
| 131 | + # Configure LoRA |
| 132 | + lora_config = LoraConfig( |
| 133 | + r=16, lora_alpha=32, lora_dropout=0.05, |
| 134 | + target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], |
| 135 | + task_type=TaskType.CAUSAL_LM, bias="none", |
| 136 | + ) |
| 137 | + peft_model = get_peft_model(model, lora_config) |
| 138 | + trainable = sum(p.numel() for p in peft_model.parameters() if p.requires_grad) |
| 139 | + total_params = sum(p.numel() for p in peft_model.parameters()) |
| 140 | + print(f" LoRA: {trainable:,}/{total_params:,} trainable") |
| 141 | + |
| 142 | + output_dir = f"/tmp/adapters/{adapter_name}" |
| 143 | + |
| 144 | + # Configure trainer |
| 145 | + if USE_NEW_TRL: |
| 146 | + training_args = SFTConfig( |
| 147 | + output_dir=output_dir, |
| 148 | + num_train_epochs=epochs, |
| 149 | + per_device_train_batch_size=2, |
| 150 | + gradient_accumulation_steps=4, |
| 151 | + learning_rate=LEARNING_RATE, |
| 152 | + warmup_ratio=0.03, |
| 153 | + logging_steps=10, |
| 154 | + save_steps=500, |
| 155 | + bf16=True, |
| 156 | + report_to="none", |
| 157 | + dataset_text_field="text", |
| 158 | + max_length=2048, |
| 159 | + ) |
| 160 | + trainer = SFTTrainer( |
| 161 | + model=peft_model, |
| 162 | + args=training_args, |
| 163 | + train_dataset=dataset, |
| 164 | + processing_class=tokenizer, |
| 165 | + ) |
| 166 | + else: |
| 167 | + training_args = TrainingArguments( |
| 168 | + output_dir=output_dir, |
| 169 | + num_train_epochs=epochs, |
| 170 | + per_device_train_batch_size=2, |
| 171 | + gradient_accumulation_steps=4, |
| 172 | + learning_rate=LEARNING_RATE, |
| 173 | + warmup_ratio=0.03, |
| 174 | + logging_steps=10, |
| 175 | + save_steps=500, |
| 176 | + bf16=True, |
| 177 | + report_to="none", |
| 178 | + ) |
| 179 | + trainer = SFTTrainer( |
| 180 | + model=peft_model, |
| 181 | + args=training_args, |
| 182 | + train_dataset=dataset, |
| 183 | + tokenizer=tokenizer, |
| 184 | + dataset_text_field="text", |
| 185 | + max_seq_length=2048, |
| 186 | + ) |
| 187 | + |
| 188 | + # Train |
| 189 | + print(f" Training...") |
| 190 | + result = trainer.train() |
| 191 | + elapsed = time.time() - start |
| 192 | + print(f" Done! Loss: {result.training_loss:.4f}, Steps: {result.global_step}, Time: {elapsed:.0f}s") |
| 193 | + |
| 194 | + # Save locally |
| 195 | + peft_model.save_pretrained(output_dir) |
| 196 | + tokenizer.save_pretrained(output_dir) |
| 197 | + print(f" Saved to {output_dir}") |
| 198 | + |
| 199 | + # Upload |
| 200 | + try: |
| 201 | + api.upload_folder( |
| 202 | + folder_path=output_dir, |
| 203 | + path_in_repo=adapter_name, |
| 204 | + repo_id=OUTPUT_REPO, |
| 205 | + token=HF_TOKEN, |
| 206 | + ) |
| 207 | + print(f" Uploaded to {OUTPUT_REPO}/{adapter_name}") |
| 208 | + except Exception as e: |
| 209 | + print(f" Upload failed: {e}") |
| 210 | + failed_uploads.append(adapter_name) |
| 211 | + |
| 212 | + results[adapter_name] = { |
| 213 | + "loss": result.training_loss, |
| 214 | + "steps": result.global_step, |
| 215 | + "time_seconds": elapsed, |
| 216 | + } |
| 217 | + |
| 218 | + # Cleanup |
| 219 | + try: |
| 220 | + model = peft_model.unload() |
| 221 | + except: |
| 222 | + model = peft_model.base_model.model |
| 223 | + del peft_model, trainer, dataset, examples |
| 224 | + gc.collect() |
| 225 | + torch.cuda.empty_cache() |
| 226 | + |
| 227 | +# Summary |
| 228 | +print(f"\n{'=' * 60}") |
| 229 | +print(f"Training Complete!") |
| 230 | +print(f"{'=' * 60}") |
| 231 | +for name, r in results.items(): |
| 232 | + print(f" {name}: loss={r['loss']:.4f}, steps={r['steps']}, time={r['time_seconds']:.0f}s") |
| 233 | + |
| 234 | +# Retry failed uploads |
| 235 | +if failed_uploads: |
| 236 | + print(f"\nRetrying {len(failed_uploads)} failed uploads...") |
| 237 | + for adapter_name in failed_uploads: |
| 238 | + output_dir = f"/tmp/adapters/{adapter_name}" |
| 239 | + try: |
| 240 | + api.upload_folder( |
| 241 | + folder_path=output_dir, |
| 242 | + path_in_repo=adapter_name, |
| 243 | + repo_id=OUTPUT_REPO, |
| 244 | + token=HF_TOKEN, |
| 245 | + ) |
| 246 | + print(f" Retry SUCCESS: {adapter_name}") |
| 247 | + except Exception as e: |
| 248 | + print(f" Retry FAILED: {adapter_name}: {e}") |
| 249 | + |
| 250 | +# Upload results |
| 251 | +try: |
| 252 | + with open("/tmp/training_results.json", "w") as f: |
| 253 | + json.dump(results, f, indent=2) |
| 254 | + api.upload_file( |
| 255 | + path_or_fileobj="/tmp/training_results.json", |
| 256 | + path_in_repo="training_results.json", |
| 257 | + repo_id=OUTPUT_REPO, |
| 258 | + token=HF_TOKEN, |
| 259 | + ) |
| 260 | + print("Results uploaded.") |
| 261 | +except Exception as e: |
| 262 | + print(f"Results upload failed: {e}") |
| 263 | + |
| 264 | +print(f"\nAdapters available at: https://huggingface.co/{OUTPUT_REPO}") |
0 commit comments