File size: 6,459 Bytes
f0cde1f | 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 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | 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!")
|