training-scripts / train_qwen3_codeforces.py
jonpauldavies's picture
Upload train_qwen3_codeforces.py with huggingface_hub
4992055 verified
Raw History Blame Contribute Delete
3.43 kB
# /// script
# dependencies = [
# "trl>=0.12.0",
# "peft>=0.7.0",
# "transformers>=4.36.0",
# "accelerate>=0.24.0",
# "datasets",
# "trackio",
# "torch",
# ]
# ///
"""
SFT training for Qwen3-0.6B on open-r1/codeforces-cots dataset.
Fine-tunes for instruction following on competitive programming tasks.
"""
import os
import trackio
from datasets import load_dataset
from peft import LoraConfig
from trl import SFTTrainer, SFTConfig
# Get HF username for model repo
HF_USERNAME = os.environ.get("HF_USERNAME", "jonpauldavies")
# Load dataset - using the configuration with editorials for richer training
print("Loading dataset...")
dataset = load_dataset(
"open-r1/codeforces-cots",
"solutions_w_editorials", # Config with editorials for better instruction data
split="train"
)
print(f"Dataset loaded: {len(dataset)} examples")
# Filter to only examples with messages (some may be empty)
dataset = dataset.filter(lambda x: x.get("messages") and len(x["messages"]) > 0)
print(f"After filtering: {len(dataset)} examples with messages")
# Limit dataset size for t4-small training
MAX_SAMPLES = 5000
if len(dataset) > MAX_SAMPLES:
dataset = dataset.shuffle(seed=42).select(range(MAX_SAMPLES))
print(f"Limited to {MAX_SAMPLES} samples for training")
# Create train/eval split
print("Creating train/eval split...")
dataset_split = dataset.train_test_split(test_size=0.05, seed=42)
train_dataset = dataset_split["train"]
eval_dataset = dataset_split["test"]
print(f"Train: {len(train_dataset)} examples")
print(f"Eval: {len(eval_dataset)} examples")
# Training configuration
config = SFTConfig(
# Hub settings - CRITICAL for saving results
output_dir="qwen3-codeforces-sft",
push_to_hub=True,
hub_model_id=f"{HF_USERNAME}/qwen3-0.6b-codeforces-sft",
hub_strategy="every_save",
hub_private_repo=False,
# Training parameters (optimized for t4-small)
num_train_epochs=1,
per_device_train_batch_size=1,
gradient_accumulation_steps=8, # Effective batch size = 8
learning_rate=2e-5,
max_length=1024, # Moderate context for t4-small memory
# Logging & checkpointing
logging_steps=25,
save_strategy="steps",
save_steps=200,
save_total_limit=2,
# Skip evaluation for demo to save memory on t4-small
# eval_strategy="steps",
# eval_steps=200,
# Optimization
warmup_ratio=0.1,
lr_scheduler_type="cosine",
gradient_checkpointing=True, # Save memory
fp16=True, # T4 doesn't support bf16, use fp16
# Monitoring with Trackio
report_to="trackio",
project="qwen3-codeforces-training",
run_name="sft-qwen3-0.6b-codeforces",
)
# LoRA configuration for efficient training
peft_config = LoraConfig(
r=32,
lora_alpha=64,
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM",
target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
)
# Initialize trainer (no eval_dataset for demo to save memory)
print("Initializing trainer...")
trainer = SFTTrainer(
model="Qwen/Qwen3-0.6B",
train_dataset=train_dataset,
args=config,
peft_config=peft_config,
)
# Train
print("Starting training...")
trainer.train()
# Push final model to Hub
print("Pushing to Hub...")
trainer.push_to_hub()
print(f"Training complete!")
print(f"Model saved to: https://huggingface.co/{HF_USERNAME}/qwen3-0.6b-codeforces-sft")