rodrigova91 commited on
Commit
35290f5
路
verified 路
1 Parent(s): 044afe0

Update train.py

Browse files
Files changed (1) hide show
  1. train.py +58 -22
train.py CHANGED
@@ -1,69 +1,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
- # Nombre del modelo hipot茅tico (aseg煤rate de que exista o de tenerlo local)
 
 
 
 
 
 
8
  model_name = "meta-llama-3-8b"
9
 
10
- # 1. Cargar el tokenizer y el modelo base
11
  tokenizer = AutoTokenizer.from_pretrained(model_name)
12
  model = AutoModelForCausalLM.from_pretrained(
13
  model_name,
14
- load_in_8bit=True, # para entrenar en 8 bits (requiere bitsandbytes)
15
- device_map="auto" # distribuye autom谩ticamente en la GPU
16
  )
17
 
18
- # 2. Preparar el modelo para entrenamiento en 8 bits
19
  model = prepare_model_for_int8_training(model)
20
 
21
- # 3. Configurar LoRA
22
  lora_config = LoraConfig(
23
  r=8,
24
  lora_alpha=32,
25
- target_modules=["q_proj","v_proj"], # M贸dulos t铆picos en la familia Llama
26
  lora_dropout=0.05,
27
  bias="none",
28
  task_type="CAUSAL_LM"
29
  )
30
  model = get_peft_model(model, lora_config)
31
 
32
- # 4. Cargar un dataset (ejemplo JSON local o uno en Hugging Face)
33
- # Ajusta a tu dataset real
34
- dataset = load_dataset("json", data_files="mis_pdfs.json", split="train")
35
-
36
- # 5. Funci贸n de tokenizaci贸n
37
  def tokenize_fn(examples):
38
  return tokenizer(examples["text"], truncation=True, max_length=512)
39
 
40
  tokenized_dataset = dataset.map(tokenize_fn, batched=True)
41
-
42
- # 6. Configurar par谩metros de entrenamiento
43
  training_args = TrainingArguments(
44
  output_dir="llama3-lora-output",
45
  per_device_train_batch_size=1,
46
  gradient_accumulation_steps=4,
47
- num_train_epochs=1, # Ajusta seg煤n tu caso
48
  learning_rate=2e-4,
49
  fp16=True, # Usa half precision
50
  logging_steps=10,
51
- evaluation_strategy="no", # Cambia a "steps" o "epoch" si tienes validaci贸n
52
  save_strategy="epoch"
53
  )
54
-
55
- # 7. Crear el Trainer
56
  trainer = Trainer(
57
  model=model,
58
  args=training_args,
59
  train_dataset=tokenized_dataset,
60
  tokenizer=tokenizer
61
  )
62
-
63
- # 8. Entrenar
64
  trainer.train()
65
-
66
- # 9. Guardar adaptadores LoRA
67
  model.save_pretrained("llama3-lora-output")
68
  print("Entrenamiento finalizado. Adaptadores guardados en 'llama3-lora-output'.")
69
 
 
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,
94
  args=training_args,
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