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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Fine-tune Qwen2.5-Coder:1.5B with QLoRA via Unsloth.
|
| 4 |
+
Designed for automated RunPod execution.
|
| 5 |
+
|
| 6 |
+
Usage:
|
| 7 |
+
python3 train_qwen15b_coder.py \\
|
| 8 |
+
--train_file /workspace/training-data/train.jsonl \\
|
| 9 |
+
--eval_file /workspace/training-data/eval.jsonl \\
|
| 10 |
+
--output_dir /workspace/qwen15b-lora-adapter \\
|
| 11 |
+
--model_name Qwen/Qwen2.5-Coder-1.5B \\
|
| 12 |
+
--lora_r 8 \\
|
| 13 |
+
--lora_alpha 16 \\
|
| 14 |
+
--batch_size 4 \\
|
| 15 |
+
--num_epochs 1
|
| 16 |
+
|
| 17 |
+
Output: LoRA adapter weights in --output_dir
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
import sys
|
| 23 |
+
import time
|
| 24 |
+
import re
|
| 25 |
+
import argparse
|
| 26 |
+
import random
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
import torch
|
| 30 |
+
from datasets import Dataset
|
| 31 |
+
from transformers import TrainingArguments
|
| 32 |
+
from unsloth import FastLanguageModel, is_bfloat16_supported
|
| 33 |
+
from trl import SFTTrainer
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# ββ Args ββ
|
| 37 |
+
def parse_args():
|
| 38 |
+
p = argparse.ArgumentParser(description="Fine-tune Qwen 1.5B with QLoRA")
|
| 39 |
+
p.add_argument("--train_file", default="/workspace/training-data/train.jsonl")
|
| 40 |
+
p.add_argument("--eval_file", default="/workspace/training-data/eval.jsonl")
|
| 41 |
+
p.add_argument("--output_dir", default="/workspace/qwen15b-lora-adapter")
|
| 42 |
+
p.add_argument("--model_name", default="unsloth/Qwen2.5-Coder-1.5B")
|
| 43 |
+
p.add_argument("--lora_r", type=int, default=8)
|
| 44 |
+
p.add_argument("--lora_alpha", type=int, default=16)
|
| 45 |
+
p.add_argument("--batch_size", type=int, default=4)
|
| 46 |
+
p.add_argument("--gradient_accumulation", type=int, default=4)
|
| 47 |
+
p.add_argument("--learning_rate", type=float, default=2e-4)
|
| 48 |
+
p.add_argument("--num_epochs", type=int, default=1)
|
| 49 |
+
p.add_argument("--max_seq_length", type=int, default=2048)
|
| 50 |
+
p.add_argument("--save_steps", type=int, default=100)
|
| 51 |
+
p.add_argument("--warmup_steps", type=int, default=20)
|
| 52 |
+
return p.parse_args()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def load_jsonl(path):
|
| 56 |
+
"""Load a JSONL file as a list of dicts."""
|
| 57 |
+
records = []
|
| 58 |
+
with open(path) as f:
|
| 59 |
+
for line in f:
|
| 60 |
+
line = line.strip()
|
| 61 |
+
if line:
|
| 62 |
+
records.append(json.loads(line))
|
| 63 |
+
return records
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def format_messages_for_training(record):
|
| 67 |
+
"""Convert messages array to prompt+response text."""
|
| 68 |
+
msgs = record.get("messages", [])
|
| 69 |
+
system = ""
|
| 70 |
+
prompt_parts = []
|
| 71 |
+
response_text = ""
|
| 72 |
+
|
| 73 |
+
for m in msgs:
|
| 74 |
+
role = m.get("role", "")
|
| 75 |
+
content = m.get("content", "")
|
| 76 |
+
if role == "system":
|
| 77 |
+
system = content
|
| 78 |
+
elif role == "user":
|
| 79 |
+
prompt_parts.append(content)
|
| 80 |
+
elif role == "assistant":
|
| 81 |
+
response_text = content
|
| 82 |
+
|
| 83 |
+
prompt = f"<|im_start|>system\n{system}<|im_end|>\n" if system else ""
|
| 84 |
+
prompt += "<|im_start|>user\n" + "\n".join(prompt_parts) + "<|im_end|>\n<|im_start|>assistant\n"
|
| 85 |
+
return prompt, response_text
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def scrub_check(records):
|
| 89 |
+
"""Verify no credentials leaked into training data."""
|
| 90 |
+
cred_patterns = [
|
| 91 |
+
r'ghp_[a-zA-Z0-9]{35,40}',
|
| 92 |
+
r'gho_[a-zA-Z0-9_]{35,40}',
|
| 93 |
+
r'github_pat_[a-zA-Z0-9_]{80,90}',
|
| 94 |
+
r'(?i)(bearer|token|authorization):\s*[a-zA-Z0-9_-]{20,}',
|
| 95 |
+
r'-----BEGIN (RSA|EC|DSA|OPENSSH|PRIVATE) KEY-----',
|
| 96 |
+
]
|
| 97 |
+
for i, r in enumerate(records):
|
| 98 |
+
text = json.dumps(r)
|
| 99 |
+
for pat in cred_patterns:
|
| 100 |
+
if re.search(pat, text):
|
| 101 |
+
print(f"β CREDENTIAL FOUND in record {i}, pattern: {pat[:30]}")
|
| 102 |
+
return False
|
| 103 |
+
return True
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def main():
|
| 107 |
+
args = parse_args()
|
| 108 |
+
|
| 109 |
+
print("=" * 60)
|
| 110 |
+
print("Qwen 1.5B Fine-Tuning via Unsloth QLoRA")
|
| 111 |
+
print("=" * 60)
|
| 112 |
+
print(f"Model: {args.model_name}")
|
| 113 |
+
print(f"Train file: {args.train_file}")
|
| 114 |
+
print(f"Eval file: {args.eval_file}")
|
| 115 |
+
print(f"Output: {args.output_dir}")
|
| 116 |
+
print(f"LoRA r={args.lora_r} alpha={args.lora_alpha}")
|
| 117 |
+
print(f"Batch={args.batch_size} grad_acc={args.gradient_accumulation}")
|
| 118 |
+
print(f"LR={args.learning_rate} epochs={args.num_epochs}")
|
| 119 |
+
print(f"Max length: {args.max_seq_length}")
|
| 120 |
+
print("")
|
| 121 |
+
|
| 122 |
+
# ββ GPU check ββ
|
| 123 |
+
if torch.cuda.is_available():
|
| 124 |
+
print(f"GPU: {torch.cuda.get_device_name(0)}")
|
| 125 |
+
print(f"VRAM: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.1f} GiB")
|
| 126 |
+
else:
|
| 127 |
+
print("WARNING: No GPU detected!")
|
| 128 |
+
print("")
|
| 129 |
+
|
| 130 |
+
# ββ Load data ββ
|
| 131 |
+
print("Loading data...")
|
| 132 |
+
train_records = load_jsonl(args.train_file)
|
| 133 |
+
eval_records = load_jsonl(args.eval_file)
|
| 134 |
+
print(f" Train: {len(train_records)} records")
|
| 135 |
+
print(f" Eval: {len(eval_records)} records")
|
| 136 |
+
|
| 137 |
+
# ββ Credential scrub check ββ
|
| 138 |
+
print("Verifying data cleanliness...")
|
| 139 |
+
all_records = train_records + eval_records
|
| 140 |
+
if not scrub_check(all_records):
|
| 141 |
+
print("β DATA NOT CLEAN β aborting!")
|
| 142 |
+
sys.exit(1)
|
| 143 |
+
print("β
Credential check passed")
|
| 144 |
+
|
| 145 |
+
# ββ Format data ββ
|
| 146 |
+
print("Formatting conversations...")
|
| 147 |
+
train_texts = []
|
| 148 |
+
for r in train_records:
|
| 149 |
+
prompt, response = format_messages_for_training(r)
|
| 150 |
+
if response:
|
| 151 |
+
train_texts.append({"prompt": prompt, "response": response})
|
| 152 |
+
|
| 153 |
+
eval_texts = []
|
| 154 |
+
for r in eval_records:
|
| 155 |
+
prompt, response = format_messages_for_training(r)
|
| 156 |
+
if response:
|
| 157 |
+
eval_texts.append({"prompt": prompt, "response": response})
|
| 158 |
+
|
| 159 |
+
print(f" Train formatted: {len(train_texts)}")
|
| 160 |
+
print(f" Eval formatted: {len(eval_texts)}")
|
| 161 |
+
|
| 162 |
+
train_dataset = Dataset.from_list(train_texts)
|
| 163 |
+
eval_dataset = Dataset.from_list(eval_texts)
|
| 164 |
+
|
| 165 |
+
# ββ Load model ββ
|
| 166 |
+
print(f"\nLoading base model: {args.model_name}")
|
| 167 |
+
model, tokenizer = FastLanguageModel.from_pretrained(
|
| 168 |
+
model_name=args.model_name,
|
| 169 |
+
max_seq_length=args.max_seq_length,
|
| 170 |
+
dtype=None,
|
| 171 |
+
load_in_4bit=True,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
# Setup tokenize function now that tokenizer exists
|
| 175 |
+
def tokenize_fn(examples):
|
| 176 |
+
texts = [
|
| 177 |
+
p + r + "<|im_end|>"
|
| 178 |
+
for p, r in zip(examples["prompt"], examples["response"])
|
| 179 |
+
]
|
| 180 |
+
return tokenizer(
|
| 181 |
+
texts,
|
| 182 |
+
truncation=True,
|
| 183 |
+
padding="max_length",
|
| 184 |
+
max_length=args.max_seq_length,
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
# ββ Apply LoRA ββ
|
| 188 |
+
print("Applying LoRA adapters...")
|
| 189 |
+
target_modules = [
|
| 190 |
+
"q_proj", "k_proj", "v_proj", "o_proj",
|
| 191 |
+
"gate_proj", "up_proj", "down_proj",
|
| 192 |
+
]
|
| 193 |
+
model = FastLanguageModel.get_peft_model(
|
| 194 |
+
model,
|
| 195 |
+
r=args.lora_r,
|
| 196 |
+
target_modules=target_modules,
|
| 197 |
+
lora_alpha=args.lora_alpha,
|
| 198 |
+
lora_dropout=0.05,
|
| 199 |
+
bias="none",
|
| 200 |
+
use_gradient_checkpointing=True,
|
| 201 |
+
random_state=42,
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 205 |
+
total = sum(p.numel() for p in model.parameters())
|
| 206 |
+
print(f" Trainable params: {trainable:,} / {total:,} ({100*trainable/total:.1f}%)")
|
| 207 |
+
|
| 208 |
+
# ββ Tokenize datasets ββ
|
| 209 |
+
print("Tokenizing datasets...")
|
| 210 |
+
train_dataset = train_dataset.map(tokenize_fn, batched=True)
|
| 211 |
+
eval_dataset = eval_dataset.map(tokenize_fn, batched=True)
|
| 212 |
+
|
| 213 |
+
# ββ Training args ββ
|
| 214 |
+
args_training = TrainingArguments(
|
| 215 |
+
per_device_train_batch_size=args.batch_size,
|
| 216 |
+
per_device_eval_batch_size=args.batch_size,
|
| 217 |
+
gradient_accumulation_steps=args.gradient_accumulation,
|
| 218 |
+
warmup_steps=args.warmup_steps,
|
| 219 |
+
num_train_epochs=args.num_epochs,
|
| 220 |
+
learning_rate=args.learning_rate,
|
| 221 |
+
fp16=not is_bfloat16_supported(),
|
| 222 |
+
bf16=is_bfloat16_supported(),
|
| 223 |
+
logging_steps=20,
|
| 224 |
+
save_steps=args.save_steps,
|
| 225 |
+
evaluation_strategy="steps",
|
| 226 |
+
eval_steps=args.save_steps,
|
| 227 |
+
output_dir=args.output_dir,
|
| 228 |
+
optim="adamw_8bit",
|
| 229 |
+
weight_decay=0.01,
|
| 230 |
+
lr_scheduler_type="cosine",
|
| 231 |
+
report_to="none",
|
| 232 |
+
save_total_limit=2,
|
| 233 |
+
load_best_model_at_end=True,
|
| 234 |
+
metric_for_best_model="eval_loss",
|
| 235 |
+
max_grad_norm=0.3,
|
| 236 |
+
seed=42,
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
# ββ Trainer ββ
|
| 240 |
+
trainer = SFTTrainer(
|
| 241 |
+
model=model,
|
| 242 |
+
tokenizer=tokenizer,
|
| 243 |
+
args=args_training,
|
| 244 |
+
train_dataset=train_dataset,
|
| 245 |
+
eval_dataset=eval_dataset,
|
| 246 |
+
max_seq_length=args.max_seq_length,
|
| 247 |
+
dataset_text_field="prompt",
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
# ββ Train ββ
|
| 251 |
+
print("\nπ Starting training...")
|
| 252 |
+
start = time.time()
|
| 253 |
+
trainer.train()
|
| 254 |
+
elapsed = time.time() - start
|
| 255 |
+
print(f"\nβ
Training completed in {elapsed/60:.1f} minutes")
|
| 256 |
+
|
| 257 |
+
# ββ Save ββ
|
| 258 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 259 |
+
model.save_pretrained(args.output_dir)
|
| 260 |
+
tokenizer.save_pretrained(args.output_dir)
|
| 261 |
+
print(f"Adapter saved to {args.output_dir}")
|
| 262 |
+
|
| 263 |
+
# ββ Provenance ββ
|
| 264 |
+
prov = {
|
| 265 |
+
"model": args.model_name,
|
| 266 |
+
"output_dir": args.output_dir,
|
| 267 |
+
"train_records": len(train_records),
|
| 268 |
+
"eval_records": len(eval_records),
|
| 269 |
+
"train_formatted": len(train_texts),
|
| 270 |
+
"eval_formatted": len(eval_texts),
|
| 271 |
+
"epochs": args.num_epochs,
|
| 272 |
+
"batch_size": args.batch_size,
|
| 273 |
+
"gradient_accumulation": args.gradient_accumulation,
|
| 274 |
+
"learning_rate": args.learning_rate,
|
| 275 |
+
"lora_r": args.lora_r,
|
| 276 |
+
"lora_alpha": args.lora_alpha,
|
| 277 |
+
"max_seq_length": args.max_seq_length,
|
| 278 |
+
"training_minutes": round(elapsed / 60, 1),
|
| 279 |
+
"trainable_params": trainable,
|
| 280 |
+
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
| 281 |
+
}
|
| 282 |
+
with open(os.path.join(args.output_dir, "training_provenance.json"), "w") as f:
|
| 283 |
+
json.dump(prov, f, indent=2)
|
| 284 |
+
|
| 285 |
+
print("\nProvenance saved.")
|
| 286 |
+
print("-" * 40)
|
| 287 |
+
print(f"Adapter: {args.output_dir}/")
|
| 288 |
+
print(f"Test: python3 -c \"from unsloth import FastLanguageModel; model, tokenizer = FastLanguageModel.from_pretrained('{args.output_dir}'); print('Loaded')\"")
|
| 289 |
+
print()
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
if __name__ == "__main__":
|
| 293 |
+
main()
|