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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# /// script
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "trl>=0.12.0",
|
| 5 |
+
# "peft>=0.7.0",
|
| 6 |
+
# "transformers>=4.45.0",
|
| 7 |
+
# "accelerate>=0.24.0",
|
| 8 |
+
# "datasets>=2.14.0",
|
| 9 |
+
# "trackio",
|
| 10 |
+
# "bitsandbytes>=0.41.0",
|
| 11 |
+
# ]
|
| 12 |
+
# ///
|
| 13 |
+
"""
|
| 14 |
+
Fine-tune Qwen3-0.6B on open-r1/codeforces-cots dataset for instruction following.
|
| 15 |
+
|
| 16 |
+
This script trains the model on competitive programming problems with chain-of-thought
|
| 17 |
+
reasoning traces generated by DeepSeek R1.
|
| 18 |
+
|
| 19 |
+
Usage:
|
| 20 |
+
Local: python train_qwen3_codeforces.py
|
| 21 |
+
|
| 22 |
+
HF Jobs CLI:
|
| 23 |
+
hf jobs uv run \
|
| 24 |
+
--flavor a10g-large \
|
| 25 |
+
--timeout 3h \
|
| 26 |
+
--secrets HF_TOKEN \
|
| 27 |
+
"https://huggingface.co/YOUR_USERNAME/training-scripts/resolve/main/train_qwen3_codeforces.py"
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
import os
|
| 31 |
+
from datasets import load_dataset
|
| 32 |
+
from peft import LoraConfig
|
| 33 |
+
from trl import SFTTrainer, SFTConfig
|
| 34 |
+
from transformers import AutoTokenizer
|
| 35 |
+
|
| 36 |
+
# Configuration
|
| 37 |
+
MODEL_NAME = "Qwen/Qwen3-0.6B"
|
| 38 |
+
DATASET_NAME = "open-r1/codeforces-cots"
|
| 39 |
+
DATASET_CONFIG = "decontaminated" # Use decontaminated version with messages format
|
| 40 |
+
OUTPUT_DIR = "qwen3-0.6b-codeforces-cots"
|
| 41 |
+
HUB_MODEL_ID = os.getenv("HUB_MODEL_ID", "apipoj-aiai/qwen3-0.6b-codeforces-cots")
|
| 42 |
+
|
| 43 |
+
# Training hyperparameters
|
| 44 |
+
NUM_TRAIN_EPOCHS = 1
|
| 45 |
+
BATCH_SIZE = 2
|
| 46 |
+
GRADIENT_ACCUMULATION_STEPS = 8 # Effective batch size = 16
|
| 47 |
+
LEARNING_RATE = 2e-5
|
| 48 |
+
MAX_SEQ_LENGTH = 2048 # Competitive programming problems can be long
|
| 49 |
+
WARMUP_RATIO = 0.1
|
| 50 |
+
|
| 51 |
+
# Dataset size limits for reasonable training time
|
| 52 |
+
MAX_TRAIN_SAMPLES = 10000 # Adjust based on time/budget constraints
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def format_codeforces_example(example):
|
| 56 |
+
"""
|
| 57 |
+
Format the codeforces-cots example into instruction-following format.
|
| 58 |
+
|
| 59 |
+
The decontaminated config has a 'messages' field with conversation format.
|
| 60 |
+
We'll use the problem description as instruction and the solution with
|
| 61 |
+
reasoning as the response.
|
| 62 |
+
"""
|
| 63 |
+
messages = example.get("messages", [])
|
| 64 |
+
|
| 65 |
+
if messages:
|
| 66 |
+
# Dataset already has messages in conversation format
|
| 67 |
+
return {"messages": messages}
|
| 68 |
+
|
| 69 |
+
# Fallback: construct from individual fields if messages not available
|
| 70 |
+
problem = example.get("description", "")
|
| 71 |
+
input_spec = example.get("input_specification", "")
|
| 72 |
+
output_spec = example.get("output_specification", "")
|
| 73 |
+
examples_text = ""
|
| 74 |
+
|
| 75 |
+
# Build the problem statement
|
| 76 |
+
problem_text = f"""## Problem
|
| 77 |
+
{problem}
|
| 78 |
+
|
| 79 |
+
## Input Specification
|
| 80 |
+
{input_spec}
|
| 81 |
+
|
| 82 |
+
## Output Specification
|
| 83 |
+
{output_spec}"""
|
| 84 |
+
|
| 85 |
+
# Get the solution with reasoning (chain-of-thought)
|
| 86 |
+
generation = example.get("generation", "")
|
| 87 |
+
|
| 88 |
+
# Format as instruction-following conversation
|
| 89 |
+
formatted_messages = [
|
| 90 |
+
{
|
| 91 |
+
"role": "user",
|
| 92 |
+
"content": f"Solve this competitive programming problem:\n\n{problem_text}"
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
"role": "assistant",
|
| 96 |
+
"content": generation
|
| 97 |
+
}
|
| 98 |
+
]
|
| 99 |
+
|
| 100 |
+
return {"messages": formatted_messages}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def main():
|
| 104 |
+
print("=" * 60)
|
| 105 |
+
print("Fine-tuning Qwen3-0.6B on CodeForces-CoTs Dataset")
|
| 106 |
+
print("=" * 60)
|
| 107 |
+
|
| 108 |
+
# Load tokenizer
|
| 109 |
+
print("\n1. Loading tokenizer...")
|
| 110 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 111 |
+
if tokenizer.pad_token is None:
|
| 112 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 113 |
+
print(f" Tokenizer loaded: {MODEL_NAME}")
|
| 114 |
+
|
| 115 |
+
# Load dataset
|
| 116 |
+
print(f"\n2. Loading dataset: {DATASET_NAME} ({DATASET_CONFIG})...")
|
| 117 |
+
dataset = load_dataset(DATASET_NAME, DATASET_CONFIG, split="train")
|
| 118 |
+
print(f" Full dataset size: {len(dataset)} examples")
|
| 119 |
+
|
| 120 |
+
# Sample if dataset is large
|
| 121 |
+
if MAX_TRAIN_SAMPLES and len(dataset) > MAX_TRAIN_SAMPLES:
|
| 122 |
+
dataset = dataset.shuffle(seed=42).select(range(MAX_TRAIN_SAMPLES))
|
| 123 |
+
print(f" Sampled to: {len(dataset)} examples")
|
| 124 |
+
|
| 125 |
+
# Inspect first example
|
| 126 |
+
print("\n3. Inspecting dataset structure...")
|
| 127 |
+
first_example = dataset[0]
|
| 128 |
+
print(f" Available columns: {list(first_example.keys())}")
|
| 129 |
+
|
| 130 |
+
# Check if messages field exists
|
| 131 |
+
if "messages" in first_example:
|
| 132 |
+
print(" Dataset has 'messages' field - using directly for SFT")
|
| 133 |
+
# Dataset already formatted, use as-is
|
| 134 |
+
else:
|
| 135 |
+
print(" Formatting dataset for instruction following...")
|
| 136 |
+
dataset = dataset.map(
|
| 137 |
+
format_codeforces_example,
|
| 138 |
+
remove_columns=dataset.column_names,
|
| 139 |
+
desc="Formatting examples"
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
# Create train/eval split
|
| 143 |
+
print("\n4. Creating train/eval split...")
|
| 144 |
+
dataset_split = dataset.train_test_split(test_size=0.05, seed=42)
|
| 145 |
+
train_dataset = dataset_split["train"]
|
| 146 |
+
eval_dataset = dataset_split["test"]
|
| 147 |
+
print(f" Train: {len(train_dataset)} examples")
|
| 148 |
+
print(f" Eval: {len(eval_dataset)} examples")
|
| 149 |
+
|
| 150 |
+
# LoRA configuration for efficient fine-tuning
|
| 151 |
+
print("\n5. Setting up LoRA configuration...")
|
| 152 |
+
peft_config = LoraConfig(
|
| 153 |
+
r=16,
|
| 154 |
+
lora_alpha=32,
|
| 155 |
+
lora_dropout=0.05,
|
| 156 |
+
bias="none",
|
| 157 |
+
task_type="CAUSAL_LM",
|
| 158 |
+
target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
|
| 159 |
+
)
|
| 160 |
+
print(f" LoRA rank: {peft_config.r}, alpha: {peft_config.lora_alpha}")
|
| 161 |
+
|
| 162 |
+
# Training configuration
|
| 163 |
+
print("\n6. Configuring training...")
|
| 164 |
+
training_config = SFTConfig(
|
| 165 |
+
output_dir=OUTPUT_DIR,
|
| 166 |
+
|
| 167 |
+
# Hub settings (CRITICAL for saving results)
|
| 168 |
+
push_to_hub=True,
|
| 169 |
+
hub_model_id=HUB_MODEL_ID,
|
| 170 |
+
hub_strategy="every_save",
|
| 171 |
+
hub_private_repo=True,
|
| 172 |
+
|
| 173 |
+
# Training parameters
|
| 174 |
+
num_train_epochs=NUM_TRAIN_EPOCHS,
|
| 175 |
+
per_device_train_batch_size=BATCH_SIZE,
|
| 176 |
+
per_device_eval_batch_size=BATCH_SIZE,
|
| 177 |
+
gradient_accumulation_steps=GRADIENT_ACCUMULATION_STEPS,
|
| 178 |
+
learning_rate=LEARNING_RATE,
|
| 179 |
+
max_seq_length=MAX_SEQ_LENGTH,
|
| 180 |
+
|
| 181 |
+
# Optimization
|
| 182 |
+
warmup_ratio=WARMUP_RATIO,
|
| 183 |
+
lr_scheduler_type="cosine",
|
| 184 |
+
optim="adamw_torch",
|
| 185 |
+
bf16=True, # Use bfloat16 for Qwen3
|
| 186 |
+
gradient_checkpointing=True,
|
| 187 |
+
|
| 188 |
+
# Logging & checkpoints
|
| 189 |
+
logging_steps=10,
|
| 190 |
+
save_strategy="steps",
|
| 191 |
+
save_steps=200,
|
| 192 |
+
save_total_limit=3,
|
| 193 |
+
|
| 194 |
+
# Evaluation
|
| 195 |
+
eval_strategy="steps",
|
| 196 |
+
eval_steps=200,
|
| 197 |
+
|
| 198 |
+
# Monitoring with Trackio
|
| 199 |
+
report_to="trackio",
|
| 200 |
+
project="qwen3-codeforces-finetune",
|
| 201 |
+
run_name="qwen3-0.6b-cots-sft",
|
| 202 |
+
|
| 203 |
+
# Other
|
| 204 |
+
seed=42,
|
| 205 |
+
dataloader_num_workers=4,
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
print(f" Output dir: {OUTPUT_DIR}")
|
| 209 |
+
print(f" Hub model ID: {HUB_MODEL_ID}")
|
| 210 |
+
print(f" Epochs: {NUM_TRAIN_EPOCHS}")
|
| 211 |
+
print(f" Effective batch size: {BATCH_SIZE * GRADIENT_ACCUMULATION_STEPS}")
|
| 212 |
+
print(f" Learning rate: {LEARNING_RATE}")
|
| 213 |
+
print(f" Max sequence length: {MAX_SEQ_LENGTH}")
|
| 214 |
+
|
| 215 |
+
# Initialize trainer
|
| 216 |
+
print("\n7. Initializing SFT Trainer...")
|
| 217 |
+
trainer = SFTTrainer(
|
| 218 |
+
model=MODEL_NAME,
|
| 219 |
+
train_dataset=train_dataset,
|
| 220 |
+
eval_dataset=eval_dataset,
|
| 221 |
+
args=training_config,
|
| 222 |
+
peft_config=peft_config,
|
| 223 |
+
processing_class=tokenizer,
|
| 224 |
+
)
|
| 225 |
+
print(" Trainer initialized successfully")
|
| 226 |
+
|
| 227 |
+
# Start training
|
| 228 |
+
print("\n" + "=" * 60)
|
| 229 |
+
print("Starting training...")
|
| 230 |
+
print("=" * 60 + "\n")
|
| 231 |
+
|
| 232 |
+
trainer.train()
|
| 233 |
+
|
| 234 |
+
# Save and push to Hub
|
| 235 |
+
print("\n8. Saving model and pushing to Hub...")
|
| 236 |
+
trainer.save_model()
|
| 237 |
+
trainer.push_to_hub()
|
| 238 |
+
|
| 239 |
+
print("\n" + "=" * 60)
|
| 240 |
+
print("Training Complete!")
|
| 241 |
+
print("=" * 60)
|
| 242 |
+
print(f"\nModel saved to: https://huggingface.co/{HUB_MODEL_ID}")
|
| 243 |
+
print(f"View training metrics at: https://huggingface.co/spaces/apipoj-aiai/trackio")
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
if __name__ == "__main__":
|
| 247 |
+
main()
|