temp_experiment / train.py
Amden's picture
Upload train.py with huggingface_hub
f0cde1f verified
Raw History Blame Contribute Delete
6.46 kB
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
print("CUDA_VISIBLE_DEVICES is set to:", os.environ["CUDA_VISIBLE_DEVICES"])
import datetime
from unsloth import FastLanguageModel
import torch
from datasets import Dataset
import pandas as pd
# 1. Configuration
max_seq_length = 6300 # Can increase for longer reasoning traces
lora_rank = 32 # Larger rank = smarter, but slower
# Load model and tokenizer for Qwen2.5-1.5B-Instruct
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = "unsloth/Qwen2.5-1.5B-Instruct",
max_seq_length = max_seq_length,
load_in_4bit = False, # False for LoRA 16bit
fast_inference = True, # Enable vLLM fast inference
max_lora_rank = lora_rank,
gpu_memory_utilization = 0.8, # Reduce if out of memory
)
# Get PEFT model
model = FastLanguageModel.get_peft_model(
model,
r = lora_rank, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
target_modules = [
"q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",
],
lora_alpha = lora_rank * 2, # *2 speeds up training
use_gradient_checkpointing = "unsloth", # Reduces memory usage
random_state = 3407,
)
print("=======================================")
reasoning_start = "<start_working_out>" # Acts as <think>
reasoning_end = "<end_working_out>" # Acts as </think>
solution_start = "<SOLUTION>"
solution_end = "</SOLUTION>"
system_prompt = f"""You are given a problem.
Think about the problem and provide your working out.
Place it between {reasoning_start} and {reasoning_end}."""
print(system_prompt)
# Setup custom chat template
chat_template = \
"{% if messages[0]['role'] == 'system' %}"\
"{{ messages[0]['content'] + eos_token }}"\
"{% set loop_messages = messages[1:] %}"\
"{% else %}"\
"{{ '{system_prompt}' + eos_token }}"\
"{% set loop_messages = messages %}"\
"{% endif %}"\
"{% for message in loop_messages %}"\
"{% if message['role'] == 'user' %}"\
"{{ message['content'] }}"\
"{% elif message['role'] == 'assistant' %}"\
"{{ message['content'] + eos_token }}"\
"{% endif %}"\
"{% endfor %}"\
"{% if add_generation_prompt %}{{ '{reasoning_start}' }}"\
"{% endif %}"
# Replace with our specific template:
chat_template = chat_template\
.replace("'{system_prompt}'", f"'{system_prompt}'")\
.replace("'{reasoning_start}'", f"'{reasoning_start}'")
tokenizer.chat_template = chat_template
# 2. Dataset Loading and Formatting
print("Loading SFT reasoning traces dataset from Hugging Face...")
from datasets import load_dataset
# Load the dataset uploaded to Hugging Face
ds_hf = load_dataset("Amden/temp_experiment", split="train")
df_local = pd.DataFrame(ds_hf)
# Select only the required columns
dataset = df_local[["input", "output"]].copy()
# Shuffle dataset
dataset = dataset.sample(frac=1, random_state=42).reset_index(drop=True)
def format_dataset(x):
problem = x["input"]
# Remove generated <think> and </think> tags if they exist
thoughts = x["output"]
thoughts = thoughts.replace("<think>", "").replace("</think>", "")
thoughts = thoughts.strip()
# Add custom formatting
final_prompt = reasoning_start + thoughts + reasoning_end
return [
{"role" : "system", "content" : system_prompt},
{"role" : "user", "content" : problem},
{"role" : "assistant", "content" : final_prompt},
]
dataset["Messages"] = dataset.apply(format_dataset, axis = 1)
print("Sample Message Structure:")
print(dataset["Messages"][0])
# Compute sequence length statistics
dataset["N"] = dataset["Messages"].apply(lambda x: len(tokenizer.apply_chat_template(x)))
print(f"Max token length in dataset: {dataset['N'].max()}")
dataset["text"] = tokenizer.apply_chat_template(dataset["Messages"].values.tolist(), tokenize = False)
dataset = Dataset.from_pandas(dataset)
# 3. Trainer Setup
from trl import SFTTrainer, SFTConfig
from transformers import TrainerCallback
class OutputSampleCallback(TrainerCallback):
def on_epoch_end(self, args, state, control, **kwargs):
print(f"\n=== Epoch {int(state.epoch)} finished ===")
# Print a sample prediction to check output quality
sample_text = tokenizer.apply_chat_template(
dataset[0]["Messages"][:2],
tokenize = False,
add_generation_prompt = True,
)
print("Sample input for generation:\n", sample_text)
from transformers import TextStreamer
output = model.generate(
**tokenizer(sample_text, return_tensors = "pt").to("cuda"),
temperature = 0,
max_new_tokens = 2048,
streamer = TextStreamer(tokenizer, skip_prompt = False),
)
print("OUTPUT:", output)
trainer = SFTTrainer(
model = model,
tokenizer = tokenizer,
train_dataset = dataset,
args = SFTConfig(
dataset_text_field = "text",
per_device_train_batch_size = 1,
gradient_accumulation_steps = 1, # Use GA to mimic batch size!
warmup_steps = 5,
num_train_epochs = 2, # Set this for 2 full training epochs
learning_rate = 3e-4, # Reduce to 2e-5 for long training runs
logging_steps = 5,
optim = "adamw_8bit",
weight_decay = 0.001,
lr_scheduler_type = "linear",
seed = 3407,
report_to = "none", # Set to 'wandb' to track experiments
),
callbacks=[OutputSampleCallback()],
)
# 4. Start Training
print("Starting SFT training...")
trainer.train()
# 5. Output Verification after Training
text = tokenizer.apply_chat_template(
dataset[0]["Messages"][:2],
tokenize = False,
add_generation_prompt = True, # Must add for generation
)
print("Running final output verification...")
from transformers import TextStreamer
output = model.generate(
**tokenizer(text, return_tensors = "pt").to("cuda"),
temperature = 0,
max_new_tokens = 2048,
streamer = TextStreamer(tokenizer, skip_prompt = False),
)
# 6. Save Model
now = datetime.datetime.now()
now_str = now.strftime("%Y%m%d_%H%M%S") # "20260705_205500"
os.makedirs("models", exist_ok=True)
model_name = f"models/unsloth_qwen2.5_1.5b_lora_{now_str}"
print(f"Saving LoRA adapter to {model_name}...")
model.save_lora(model_name)
print("Training and saving complete!")