Lrodriolivera commited on
Commit
13b5120
·
verified ·
1 Parent(s): 7b96638

Update training script

Browse files
Files changed (1) hide show
  1. app.py +164 -0
app.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ # Configuración crítica para PyTorch y bitsandbytes
4
+ os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:256"
5
+ os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
6
+
7
+ # Asegurarse de que bitsandbytes pueda encontrar las librerías CUDA
8
+ os.environ["LD_LIBRARY_PATH"] = "/usr/local/cuda/lib64:/usr/lib/x86_64-linux-gnu"
9
+
10
+ # Ejecutar setup.sh si no se ha hecho
11
+ if not os.path.exists(".setup_done"):
12
+ print("🔧 Ejecutando instalación de dependencias...")
13
+ os.system("bash setup.sh")
14
+ open(".setup_done", "w").write("done")
15
+ print("✅ Instalación completada. Reiniciando...")
16
+
17
+ # Importar librerías después de la instalación
18
+ import gradio as gr
19
+ from datasets import load_dataset
20
+ from transformers import (
21
+ AutoTokenizer,
22
+ AutoModelForCausalLM,
23
+ TrainingArguments,
24
+ BitsAndBytesConfig
25
+ )
26
+ from peft import LoraConfig, get_peft_model
27
+ from trl import SFTTrainer
28
+ import torch
29
+
30
+
31
+ def start_training():
32
+ yield "🔄 Iniciando entrenamiento de luc1-7B-FinChile..."
33
+
34
+ # --- 1. Cargar el dataset ---
35
+ try:
36
+ dataset = load_dataset("Lrodriolivera/luc1K-1K")["train"]
37
+ total_samples = len(dataset)
38
+ yield f"✅ Dataset cargado: {total_samples} ejemplos"
39
+ except Exception as e:
40
+ yield f"❌ Error al cargar el dataset: {e}"
41
+ return
42
+
43
+ # --- 2. Cargar el modelo base en 4-bit ---
44
+ model_name = "Qwen/Qwen2.5-7B-Instruct"
45
+ yield "🔽 Descargando y cuantizando modelo base en 4-bit..."
46
+
47
+ try:
48
+ # Configuración de cuantización 4-bit (NF4)
49
+ bnb_config = BitsAndBytesConfig(
50
+ load_in_4bit=True,
51
+ bnb_4bit_quant_type="nf4",
52
+ bnb_4bit_compute_dtype=torch.bfloat16,
53
+ bnb_4bit_use_double_quant=True,
54
+ )
55
+
56
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
57
+ model = AutoModelForCausalLM.from_pretrained(
58
+ model_name,
59
+ quantization_config=bnb_config,
60
+ device_map="auto",
61
+ trust_remote_code=False,
62
+ )
63
+ model.gradient_checkpointing_enable()
64
+ yield "✅ Modelo base cargado en 4-bit con gradient checkpointing"
65
+ except Exception as e:
66
+ yield f"❌ Error al cargar el modelo base: {e}"
67
+ return
68
+
69
+ # --- 3. Configurar LoRA ---
70
+ try:
71
+ lora_config = LoraConfig(
72
+ r=64,
73
+ lora_alpha=16,
74
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
75
+ lora_dropout=0.05,
76
+ bias="none",
77
+ task_type="CAUSAL_LM"
78
+ )
79
+ model = get_peft_model(model, lora_config)
80
+ yield "✅ Modelo configurado con LoRA"
81
+ except Exception as e:
82
+ yield f"❌ Error al configurar LoRA: {e}"
83
+ return
84
+
85
+ # --- 4. Formato de prompts ---
86
+ def formatting_prompts_func(example):
87
+ text = f"<|im_start|>user\n{example['question']}<|im_start|>think\n{example['reasoning']}<|im_start|>answer\n{example['answer']}"
88
+ return {"text": text}
89
+
90
+ try:
91
+ dataset = dataset.map(formatting_prompts_func, remove_columns=dataset.column_names)
92
+ yield "✅ Datos formateados para entrenamiento"
93
+ except Exception as e:
94
+ yield f"❌ Error al formatear datos: {e}"
95
+ return
96
+
97
+ # --- 5. Configurar entrenamiento ---
98
+ # Ajuste de max_steps: ~5 épocas con 710 ejemplos y batch_size efectivo = 16
99
+ max_steps = int((len(dataset) / 16) * 5)
100
+
101
+ training_args = TrainingArguments(
102
+ output_dir="luc1-7B-FinChile",
103
+ per_device_train_batch_size=1,
104
+ gradient_accumulation_steps=16,
105
+ learning_rate=2e-5,
106
+ lr_scheduler_type="cosine",
107
+ warmup_steps=10,
108
+ max_steps=max_steps,
109
+ fp16=True,
110
+ logging_steps=10,
111
+ save_strategy="no",
112
+ report_to="none",
113
+ run_name="luc1-training",
114
+ weight_decay=0.01,
115
+ max_grad_norm=1.0,
116
+ dataloader_num_workers=1,
117
+ optim="paged_adamw_8bit", # Usa menos memoria
118
+ )
119
+
120
+ # --- 6. Inicializar SFTTrainer ---
121
+ try:
122
+ trainer = SFTTrainer(
123
+ model=model,
124
+ args=training_args,
125
+ train_dataset=dataset,
126
+ dataset_text_field="text",
127
+ tokenizer=tokenizer,
128
+ max_seq_length=4096,
129
+ )
130
+ yield f"✅ Trainer configurado: {max_steps} pasos (~5 épocas)"
131
+ except Exception as e:
132
+ yield f"❌ Error al configurar el trainer: {e}"
133
+ return
134
+
135
+ # --- 7. Entrenar ---
136
+ yield "🔥 Iniciando entrenamiento..."
137
+ try:
138
+ trainer.train()
139
+ yield "✅ Entrenamiento completado con éxito"
140
+ except Exception as e:
141
+ yield f"❌ Error durante el entrenamiento: {e}"
142
+ return
143
+
144
+ # --- 8. Subir a Hugging Face ---
145
+ yield "📤 Subiendo modelo a Hugging Face..."
146
+ try:
147
+ model.push_to_hub("Lrodriolivera/luc1-7B-FinChile")
148
+ tokenizer.push_to_hub("Lrodriolivera/luc1-7B-FinChile")
149
+ yield "🎉 ¡Éxito! Modelo subido: https://huggingface.co/Lrodriolivera/luc1-7B-FinChile"
150
+ except Exception as e:
151
+ yield f"❌ Error al subir el modelo: {e}"
152
+
153
+
154
+ # --- Interfaz Gradio ---
155
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
156
+ gr.Markdown("# 🚀 Entrenamiento de luc1-7B-FinChile")
157
+ gr.Markdown("Presiona el botón para iniciar el entrenamiento con QLoRA en 4-bit.")
158
+ btn = gr.Button("Iniciar Entrenamiento", variant="primary")
159
+ output = gr.Textbox(label="Estado del entrenamiento", lines=20, max_lines=50)
160
+ btn.click(fn=start_training, outputs=output)
161
+
162
+ # Lanzar la app
163
+ if __name__ == "__main__":
164
+ demo.launch()