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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""DoRA Fine-tuning Script for Qwen3-4B"""
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import argparse
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import yaml
|
| 11 |
+
from datasets import load_dataset
|
| 12 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 13 |
+
from peft import LoraConfig, get_peft_model, TaskType
|
| 14 |
+
from trl import SFTTrainer, SFTConfig
|
| 15 |
+
|
| 16 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 17 |
+
|
| 18 |
+
def load_config(config_path: str) -> dict:
|
| 19 |
+
with open(config_path) as f:
|
| 20 |
+
return yaml.safe_load(f)
|
| 21 |
+
|
| 22 |
+
def setup_model_and_tokenizer(config: dict):
|
| 23 |
+
model_name = config["base_model"]
|
| 24 |
+
print(f"Loading model: {model_name}")
|
| 25 |
+
|
| 26 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 27 |
+
model_name,
|
| 28 |
+
trust_remote_code=config.get("trust_remote_code", True),
|
| 29 |
+
padding_side="right",
|
| 30 |
+
)
|
| 31 |
+
if tokenizer.pad_token is None:
|
| 32 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 33 |
+
|
| 34 |
+
model_kwargs = {
|
| 35 |
+
"trust_remote_code": config.get("trust_remote_code", True),
|
| 36 |
+
"torch_dtype": torch.bfloat16,
|
| 37 |
+
"device_map": "auto",
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, **model_kwargs)
|
| 41 |
+
|
| 42 |
+
if config.get("gradient_checkpointing", True):
|
| 43 |
+
model.gradient_checkpointing_enable()
|
| 44 |
+
|
| 45 |
+
peft_config = LoraConfig(
|
| 46 |
+
task_type=TaskType.CAUSAL_LM,
|
| 47 |
+
r=config.get("lora_r", 64),
|
| 48 |
+
lora_alpha=config.get("lora_alpha", 128),
|
| 49 |
+
lora_dropout=config.get("lora_dropout", 0.05),
|
| 50 |
+
target_modules=config.get("lora_target_modules", [
|
| 51 |
+
"q_proj", "k_proj", "v_proj", "o_proj",
|
| 52 |
+
"gate_proj", "up_proj", "down_proj"
|
| 53 |
+
]),
|
| 54 |
+
use_dora=True,
|
| 55 |
+
bias="none",
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
model = get_peft_model(model, peft_config)
|
| 59 |
+
model.print_trainable_parameters()
|
| 60 |
+
|
| 61 |
+
return model, tokenizer
|
| 62 |
+
|
| 63 |
+
def load_datasets(config: dict):
|
| 64 |
+
script_dir = Path(__file__).parent.parent
|
| 65 |
+
train_path = script_dir / config["datasets"][0]["path"]
|
| 66 |
+
val_path = script_dir / config["datasets"][1]["path"]
|
| 67 |
+
|
| 68 |
+
print(f"Loading training data from: {train_path}")
|
| 69 |
+
print(f"Loading validation data from: {val_path}")
|
| 70 |
+
|
| 71 |
+
train_dataset = load_dataset("json", data_files=str(train_path), split="train")
|
| 72 |
+
val_dataset = load_dataset("json", data_files=str(val_path), split="train")
|
| 73 |
+
|
| 74 |
+
print(f"Training samples: {len(train_dataset):,}")
|
| 75 |
+
print(f"Validation samples: {len(val_dataset):,}")
|
| 76 |
+
|
| 77 |
+
return train_dataset, val_dataset
|
| 78 |
+
|
| 79 |
+
def format_chat(example, tokenizer):
|
| 80 |
+
messages = example["messages"]
|
| 81 |
+
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
|
| 82 |
+
return {"text": text}
|
| 83 |
+
|
| 84 |
+
def main():
|
| 85 |
+
parser = argparse.ArgumentParser()
|
| 86 |
+
parser.add_argument("--config", type=str, default="config.yaml")
|
| 87 |
+
parser.add_argument("--resume", type=str, help="Resume from checkpoint")
|
| 88 |
+
args = parser.parse_args()
|
| 89 |
+
|
| 90 |
+
config_path = Path(__file__).parent / args.config
|
| 91 |
+
config = load_config(config_path)
|
| 92 |
+
|
| 93 |
+
print("=" * 60)
|
| 94 |
+
print("DoRA Fine-tuning for Qwen3-4B")
|
| 95 |
+
print("=" * 60)
|
| 96 |
+
print(f"Model: {config['base_model']}")
|
| 97 |
+
print(f"Epochs: {config['num_epochs']}")
|
| 98 |
+
print(f"LR: {config['learning_rate']}")
|
| 99 |
+
print(f"Batch: {config['micro_batch_size']} x {config['gradient_accumulation_steps']} = {config['micro_batch_size'] * config['gradient_accumulation_steps']}")
|
| 100 |
+
print(f"DoRA rank: {config['lora_r']}")
|
| 101 |
+
|
| 102 |
+
print("\n" + "-" * 40)
|
| 103 |
+
print("Loading model...")
|
| 104 |
+
model, tokenizer = setup_model_and_tokenizer(config)
|
| 105 |
+
|
| 106 |
+
print("\n" + "-" * 40)
|
| 107 |
+
print("Loading datasets...")
|
| 108 |
+
train_dataset, val_dataset = load_datasets(config)
|
| 109 |
+
|
| 110 |
+
print("Formatting datasets...")
|
| 111 |
+
train_dataset = train_dataset.map(
|
| 112 |
+
lambda x: format_chat(x, tokenizer),
|
| 113 |
+
remove_columns=train_dataset.column_names,
|
| 114 |
+
num_proc=4
|
| 115 |
+
)
|
| 116 |
+
val_dataset = val_dataset.map(
|
| 117 |
+
lambda x: format_chat(x, tokenizer),
|
| 118 |
+
remove_columns=val_dataset.column_names,
|
| 119 |
+
num_proc=4
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
output_dir = Path(__file__).parent.parent / config["output_dir"]
|
| 123 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 124 |
+
|
| 125 |
+
# Use SFTConfig instead of TrainingArguments
|
| 126 |
+
sft_config = SFTConfig(
|
| 127 |
+
output_dir=str(output_dir),
|
| 128 |
+
num_train_epochs=config["num_epochs"],
|
| 129 |
+
per_device_train_batch_size=config["micro_batch_size"],
|
| 130 |
+
per_device_eval_batch_size=config.get("eval_batch_size", config["micro_batch_size"]),
|
| 131 |
+
gradient_accumulation_steps=config["gradient_accumulation_steps"],
|
| 132 |
+
learning_rate=config["learning_rate"],
|
| 133 |
+
lr_scheduler_type=config.get("lr_scheduler", "cosine"),
|
| 134 |
+
warmup_ratio=config.get("warmup_ratio", 0.05),
|
| 135 |
+
weight_decay=config.get("weight_decay", 0.01),
|
| 136 |
+
max_grad_norm=config.get("max_grad_norm", 1.0),
|
| 137 |
+
bf16=config.get("bf16", True),
|
| 138 |
+
tf32=config.get("tf32", True),
|
| 139 |
+
logging_steps=config.get("logging_steps", 50),
|
| 140 |
+
eval_strategy="steps",
|
| 141 |
+
eval_steps=config.get("eval_steps", 500),
|
| 142 |
+
save_strategy="steps",
|
| 143 |
+
save_steps=config.get("save_steps", 500),
|
| 144 |
+
save_total_limit=config.get("save_total_limit", 3),
|
| 145 |
+
load_best_model_at_end=True,
|
| 146 |
+
metric_for_best_model="eval_loss",
|
| 147 |
+
greater_is_better=False,
|
| 148 |
+
report_to=config.get("report_to", "tensorboard"),
|
| 149 |
+
run_name=f"dora-{datetime.now().strftime('%Y%m%d_%H%M')}",
|
| 150 |
+
dataloader_num_workers=config.get("dataloader_num_workers", 4),
|
| 151 |
+
seed=config.get("seed", 42),
|
| 152 |
+
gradient_checkpointing=config.get("gradient_checkpointing", True),
|
| 153 |
+
optim=config.get("optimizer", "adamw_torch_fused"),
|
| 154 |
+
max_length=config.get("sequence_len", 1024),
|
| 155 |
+
packing=False,
|
| 156 |
+
dataset_text_field="text",
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
print("\n" + "-" * 40)
|
| 160 |
+
print("Setting up trainer...")
|
| 161 |
+
trainer = SFTTrainer(
|
| 162 |
+
model=model,
|
| 163 |
+
args=sft_config,
|
| 164 |
+
train_dataset=train_dataset,
|
| 165 |
+
eval_dataset=val_dataset,
|
| 166 |
+
processing_class=tokenizer,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
print("\n" + "=" * 60)
|
| 170 |
+
print("Starting training...")
|
| 171 |
+
print("=" * 60)
|
| 172 |
+
|
| 173 |
+
if args.resume:
|
| 174 |
+
trainer.train(resume_from_checkpoint=args.resume)
|
| 175 |
+
else:
|
| 176 |
+
trainer.train()
|
| 177 |
+
|
| 178 |
+
print("\nSaving final model...")
|
| 179 |
+
final_path = output_dir / "final"
|
| 180 |
+
trainer.save_model(str(final_path))
|
| 181 |
+
tokenizer.save_pretrained(str(final_path))
|
| 182 |
+
print(f"Model saved to: {final_path}")
|
| 183 |
+
print("\nTraining complete!")
|
| 184 |
+
|
| 185 |
+
if __name__ == "__main__":
|
| 186 |
+
main()
|