File size: 3,428 Bytes
4992055
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# /// 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")