Spaces:
Sleeping
Sleeping
Create fine_tune.py
Browse files- fine_tune.py +60 -0
fine_tune.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, Trainer
|
| 3 |
+
from peft import LoraConfig, get_peft_model
|
| 4 |
+
from datasets import load_dataset
|
| 5 |
+
|
| 6 |
+
# Load model and tokenizer
|
| 7 |
+
model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
|
| 8 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 9 |
+
|
| 10 |
+
# Use 4-bit quantization to save RAM
|
| 11 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 12 |
+
model_name,
|
| 13 |
+
load_in_4bit=True, # ✅ Reduce VRAM usage
|
| 14 |
+
device_map="cpu" # ✅ Force CPU usage
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# Apply LoRA configuration
|
| 18 |
+
lora_config = LoraConfig(
|
| 19 |
+
r=8, # Low-rank dimension (small)
|
| 20 |
+
lora_alpha=32,
|
| 21 |
+
lora_dropout=0.05,
|
| 22 |
+
bias="none",
|
| 23 |
+
task_type="CAUSAL_LM" # For TinyLlama (Chat models)
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
model = get_peft_model(model, lora_config)
|
| 27 |
+
|
| 28 |
+
# Load dataset (Example: "Hello world" text)
|
| 29 |
+
dataset = load_dataset("Abirate/english_quotes", split="train[:1000]")
|
| 30 |
+
|
| 31 |
+
def tokenize_function(examples):
|
| 32 |
+
return tokenizer(examples["quote"], padding="max_length", truncation=True, max_length=128)
|
| 33 |
+
|
| 34 |
+
tokenized_datasets = dataset.map(tokenize_function, batched=True)
|
| 35 |
+
|
| 36 |
+
# Training arguments
|
| 37 |
+
training_args = TrainingArguments(
|
| 38 |
+
output_dir="./tinyllama_lora",
|
| 39 |
+
per_device_train_batch_size=2, # ✅ Small batch size for CPU
|
| 40 |
+
num_train_epochs=1,
|
| 41 |
+
save_steps=10,
|
| 42 |
+
logging_steps=10,
|
| 43 |
+
optim="adamw_torch", # ✅ Better optimizer
|
| 44 |
+
save_total_limit=1,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
# Trainer
|
| 48 |
+
trainer = Trainer(
|
| 49 |
+
model=model,
|
| 50 |
+
args=training_args,
|
| 51 |
+
train_dataset=tokenized_datasets
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
# Start training
|
| 55 |
+
trainer.train()
|
| 56 |
+
|
| 57 |
+
# Save the fine-tuned model
|
| 58 |
+
model.save_pretrained("./tinyllama_lora_finetuned")
|
| 59 |
+
tokenizer.save_pretrained("./tinyllama_lora_finetuned")
|
| 60 |
+
print("✅ Fine-tuning complete! Model saved.")
|