-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.py
More file actions
103 lines (87 loc) · 3.54 KB
/
Copy pathtrain.py
File metadata and controls
103 lines (87 loc) · 3.54 KB
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
import torch
# Patch temporanea per PyTorch < 2.6
for i in range(1, 8):
if not hasattr(torch, f'int{i}'):
setattr(torch, f'int{i}', torch.int8)
# Ora puoi importare unsloth in sicurezza
from unsloth import FastLanguageModel
from unsloth import FastLanguageModel
from datasets import load_dataset
from trl import SFTTrainer
from transformers import TrainingArguments
from unsloth import is_bfloat16_supported
# 1. PARAMETRI DI BASE
max_seq_length = 2048 # Limite di token per farcela stare in 8GB di VRAM
print("=== 1. Caricamento del Modello Qwen in 4-bit ===")
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = "unsloth/Qwen2.5-Coder-7B-Instruct",
max_seq_length = max_seq_length,
dtype = None,
load_in_4bit = True,
)
print("=== 2. Configurazione degli Adapter QLoRA ===")
model = FastLanguageModel.get_peft_model(
model,
r = 16, # Dimensione della matrice di apprendimento
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",],
lora_alpha = 16,
lora_dropout = 0,
bias = "none",
use_gradient_checkpointing = "unsloth", # Cruciale per la RTX 4060
)
print("=== 3. Preparazione del Dataset Aziendale ===")
# Il template di istruzioni che il modello userà per imparare
alpaca_prompt = """Di seguito è riportata un'istruzione che descrive un task aziendale, accompagnata da un input che fornisce ulteriore contesto. Scrivi una risposta che completi adeguatamente la richiesta.
### Istruzione:
{}
### Input:
{}
### Risposta:
{}"""
EOS_TOKEN = tokenizer.eos_token # Impedisce al modello di generare testo all'infinito
def formatting_prompts_func(examples):
instructions = examples["instruction"]
inputs = examples["input"]
outputs = examples["output"]
texts = []
for instruction, input, output in zip(instructions, inputs, outputs):
text = alpaca_prompt.format(instruction, input, output) + EOS_TOKEN
texts.append(text)
return { "text" : texts, }
# Carica il file JSONL creato prima
dataset = load_dataset("json", data_files={"train": "dati.jsonl"}, split="train")
dataset = dataset.map(formatting_prompts_func, batched = True)
print("=== 4. Configurazione Motore di Addestramento ===")
trainer = SFTTrainer(
model = model,
tokenizer = tokenizer,
train_dataset = dataset,
dataset_text_field = "text",
max_seq_length = max_seq_length,
dataset_num_proc = 2,
packing = False,
args = TrainingArguments(
per_device_train_batch_size = 2, # Mantenuto basso per gli 8GB di VRAM
gradient_accumulation_steps = 4, # Moltiplicatore virtuale del batch size
warmup_steps = 5,
max_steps = 60, # Numero di cicli (modifica questo valore per training più lunghi)
learning_rate = 2e-4,
fp16 = not is_bfloat16_supported(),
bf16 = is_bfloat16_supported(),
logging_steps = 1,
optim = "adamw_8bit", # Ottimizzatore a 8-bit per risparmiare ulteriore memoria
weight_decay = 0.01,
lr_scheduler_type = "linear",
seed = 3407,
output_dir = "outputs",
report_to = "none", # Evita richieste API a sistemi esterni (privacy aziendale)
),
)
print("=== 5. INIZIO FINE-TUNING SULLA RTX 4060! ===")
trainer_stats = trainer.train()
print("=== 6. Salvataggio del nuovo Modello ===")
# Salva gli adapter LoRA addestrati in una cartella locale
model.save_pretrained("qwen-modello-aziendale")
tokenizer.save_pretrained("qwen-modello-aziendale")
print("Finito! Il tuo modello aziendale è stato salvato con successo.")