rodrigova91 commited on
Commit
b92e9ba
路
verified 路
1 Parent(s): 0b25a5b

Update train.py

Browse files
Files changed (1) hide show
  1. train.py +42 -64
train.py CHANGED
@@ -1,93 +1,71 @@
1
- import os
2
- import json
3
- from pathlib import Path
4
- from pypdf import PdfReader
5
  import torch
6
  from datasets import load_dataset
7
  from transformers import AutoTokenizer, AutoModelForCausalLM, TrainingArguments, Trainer
8
  from peft import LoraConfig, get_peft_model, prepare_model_for_int8_training
9
 
10
- def extract_text_from_pdf(pdf_path):
11
- """Extrae el texto de un PDF usando pypdf."""
12
- reader = PdfReader(pdf_path)
13
- text = ""
14
- for page in reader.pages:
15
- page_text = page.extract_text()
16
- if page_text:
17
- text += page_text + "\n"
18
- return text
19
-
20
- def create_dataset_from_pdfs(pdf_dir, output_json):
21
- """
22
- Recorre la carpeta pdf_dir, extrae el texto de cada PDF y lo guarda en un archivo JSON.
23
- Cada documento se guarda como un diccionario con 'filename' y 'text'.
24
- """
25
- documentos = []
26
- for archivo in os.listdir(pdf_dir):
27
- if archivo.lower().endswith(".pdf"):
28
- ruta_pdf = Path(pdf_dir) / archivo
29
- texto = extract_text_from_pdf(ruta_pdf)
30
- documentos.append({"filename": archivo, "text": texto})
31
- # Guardar los documentos en un archivo JSON
32
- with open(output_json, "w", encoding="utf-8") as f:
33
- json.dump(documentos, f, ensure_ascii=False, indent=2)
34
- print(f"Se ha creado el archivo {output_json} con {len(documentos)} documentos.")
35
-
36
  def main():
37
- # --- Paso 1: Extraer textos de PDFs y crear el dataset JSON ---
38
- pdf_directory = "ruta_a_tus_pdfs" # <-- Actualiza esta ruta con el directorio donde est谩n tus PDFs
39
- json_dataset = "mis_pdfs.json"
40
- create_dataset_from_pdfs(pdf_directory, json_dataset)
41
-
42
- # --- Paso 2: Configuraci贸n y carga del modelo ---
43
- # Nombre del modelo hipot茅tico (aseg煤rate de tener acceso o de tenerlo local)
44
- model_name = "meta-llama-3-8b"
45
-
46
- # Cargar el tokenizer y el modelo base
 
 
47
  tokenizer = AutoTokenizer.from_pretrained(model_name)
48
  model = AutoModelForCausalLM.from_pretrained(
49
  model_name,
50
- load_in_8bit=True, # Entrenamiento en 8 bits (requiere bitsandbytes)
51
- device_map="auto" # Distribuye autom谩ticamente en la GPU
52
  )
53
-
54
  # Preparar el modelo para entrenamiento en 8 bits
55
  model = prepare_model_for_int8_training(model)
56
-
57
- # Configurar LoRA
 
 
58
  lora_config = LoraConfig(
59
  r=8,
60
  lora_alpha=32,
61
- target_modules=["q_proj", "v_proj"], # M贸dulos t铆picos en la familia Llama
62
  lora_dropout=0.05,
63
  bias="none",
64
  task_type="CAUSAL_LM"
65
  )
66
  model = get_peft_model(model, lora_config)
67
-
68
- # --- Paso 3: Cargar y tokenizar el dataset extra铆do ---
69
- # Cargar el dataset generado a partir del JSON de PDFs
70
- dataset = load_dataset("json", data_files=json_dataset, split="train")
71
-
 
 
72
  # Funci贸n de tokenizaci贸n
73
- def tokenize_fn(examples):
74
- return tokenizer(examples["text"], truncation=True, max_length=512)
75
-
76
  tokenized_dataset = dataset.map(tokenize_fn, batched=True)
77
-
78
- # --- Paso 4: Configuraci贸n del entrenamiento ---
 
 
79
  training_args = TrainingArguments(
80
  output_dir="llama3-lora-output",
81
  per_device_train_batch_size=1,
82
  gradient_accumulation_steps=4,
83
- num_train_epochs=1, # Ajusta seg煤n tus necesidades
84
  learning_rate=2e-4,
85
- fp16=True, # Usa half precision
86
  logging_steps=10,
87
- evaluation_strategy="no", # Cambia a "steps" o "epoch" si dispones de validaci贸n
88
  save_strategy="epoch"
89
  )
90
-
91
  # Crear el Trainer
92
  trainer = Trainer(
93
  model=model,
@@ -95,11 +73,11 @@ def main():
95
  train_dataset=tokenized_dataset,
96
  tokenizer=tokenizer
97
  )
98
-
99
- # --- Paso 5: Entrenamiento y guardado ---
 
 
100
  trainer.train()
101
-
102
- # Guardar los adaptadores LoRA
103
  model.save_pretrained("llama3-lora-output")
104
  print("Entrenamiento finalizado. Adaptadores guardados en 'llama3-lora-output'.")
105
 
 
 
 
 
 
1
  import torch
2
  from datasets import load_dataset
3
  from transformers import AutoTokenizer, AutoModelForCausalLM, TrainingArguments, Trainer
4
  from peft import LoraConfig, get_peft_model, prepare_model_for_int8_training
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  def main():
7
+ # ---------------------------------------------------------
8
+ # Paso 1: Indicar d贸nde est谩 tu JSON (local o en Hugging Face)
9
+ # ---------------------------------------------------------
10
+ # Opci贸n A: Local
11
+ dataset_path = {"train": "mis_pdfs.json"}
12
+ # Opci贸n B: Hugging Face (ejemplo: alphasoft1/pdf, con mis_pdfs.json dentro)
13
+ # dataset_path = {"train": "alphasoft1/pdf", "data_files": "mis_pdfs.json"}
14
+
15
+ # ---------------------------------------------------------
16
+ # Paso 2: Cargar el modelo base
17
+ # ---------------------------------------------------------
18
+ model_name = "meta-llama-3-8b" # Ajusta al modelo que tengas
19
  tokenizer = AutoTokenizer.from_pretrained(model_name)
20
  model = AutoModelForCausalLM.from_pretrained(
21
  model_name,
22
+ load_in_8bit=True, # Para entrenamiento 8 bits (bitsandbytes)
23
+ device_map="auto"
24
  )
25
+
26
  # Preparar el modelo para entrenamiento en 8 bits
27
  model = prepare_model_for_int8_training(model)
28
+
29
+ # ---------------------------------------------------------
30
+ # Paso 3: Configurar LoRA
31
+ # ---------------------------------------------------------
32
  lora_config = LoraConfig(
33
  r=8,
34
  lora_alpha=32,
35
+ target_modules=["q_proj", "v_proj"], # T铆picos en Llama
36
  lora_dropout=0.05,
37
  bias="none",
38
  task_type="CAUSAL_LM"
39
  )
40
  model = get_peft_model(model, lora_config)
41
+
42
+ # ---------------------------------------------------------
43
+ # Paso 4: Cargar y tokenizar el dataset
44
+ # ---------------------------------------------------------
45
+ # Si tu JSON est谩 local:
46
+ dataset = load_dataset("json", data_files=dataset_path["train"], split="train")
47
+
48
  # Funci贸n de tokenizaci贸n
49
+ def tokenize_fn(example):
50
+ return tokenizer(example["text"], truncation=True, max_length=512)
51
+
52
  tokenized_dataset = dataset.map(tokenize_fn, batched=True)
53
+
54
+ # ---------------------------------------------------------
55
+ # Paso 5: Configuraci贸n de entrenamiento
56
+ # ---------------------------------------------------------
57
  training_args = TrainingArguments(
58
  output_dir="llama3-lora-output",
59
  per_device_train_batch_size=1,
60
  gradient_accumulation_steps=4,
61
+ num_train_epochs=1, # Ajusta seg煤n tu caso
62
  learning_rate=2e-4,
63
+ fp16=True, # Half precision
64
  logging_steps=10,
65
+ evaluation_strategy="no", # Cambia a "steps"/"epoch" si tienes validaci贸n
66
  save_strategy="epoch"
67
  )
68
+
69
  # Crear el Trainer
70
  trainer = Trainer(
71
  model=model,
 
73
  train_dataset=tokenized_dataset,
74
  tokenizer=tokenizer
75
  )
76
+
77
+ # ---------------------------------------------------------
78
+ # Paso 6: Entrenar y guardar
79
+ # ---------------------------------------------------------
80
  trainer.train()
 
 
81
  model.save_pretrained("llama3-lora-output")
82
  print("Entrenamiento finalizado. Adaptadores guardados en 'llama3-lora-output'.")
83