Upload 5 files
Browse files- README (1).md +202 -0
- adapter_config (2).json +34 -0
- special_tokens_map.json +23 -0
- tokenizer.json +0 -0
- training_llama_3_1.py +232 -0
README (1).md
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
base_model: unsloth/meta-llama-3.1-8b-instruct-bnb-4bit
|
3 |
+
library_name: peft
|
4 |
+
---
|
5 |
+
|
6 |
+
# Model Card for Model ID
|
7 |
+
|
8 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
9 |
+
|
10 |
+
|
11 |
+
|
12 |
+
## Model Details
|
13 |
+
|
14 |
+
### Model Description
|
15 |
+
|
16 |
+
<!-- Provide a longer summary of what this model is. -->
|
17 |
+
|
18 |
+
|
19 |
+
|
20 |
+
- **Developed by:** [More Information Needed]
|
21 |
+
- **Funded by [optional]:** [More Information Needed]
|
22 |
+
- **Shared by [optional]:** [More Information Needed]
|
23 |
+
- **Model type:** [More Information Needed]
|
24 |
+
- **Language(s) (NLP):** [More Information Needed]
|
25 |
+
- **License:** [More Information Needed]
|
26 |
+
- **Finetuned from model [optional]:** [More Information Needed]
|
27 |
+
|
28 |
+
### Model Sources [optional]
|
29 |
+
|
30 |
+
<!-- Provide the basic links for the model. -->
|
31 |
+
|
32 |
+
- **Repository:** [More Information Needed]
|
33 |
+
- **Paper [optional]:** [More Information Needed]
|
34 |
+
- **Demo [optional]:** [More Information Needed]
|
35 |
+
|
36 |
+
## Uses
|
37 |
+
|
38 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
39 |
+
|
40 |
+
### Direct Use
|
41 |
+
|
42 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
43 |
+
|
44 |
+
[More Information Needed]
|
45 |
+
|
46 |
+
### Downstream Use [optional]
|
47 |
+
|
48 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
49 |
+
|
50 |
+
[More Information Needed]
|
51 |
+
|
52 |
+
### Out-of-Scope Use
|
53 |
+
|
54 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
55 |
+
|
56 |
+
[More Information Needed]
|
57 |
+
|
58 |
+
## Bias, Risks, and Limitations
|
59 |
+
|
60 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
61 |
+
|
62 |
+
[More Information Needed]
|
63 |
+
|
64 |
+
### Recommendations
|
65 |
+
|
66 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
67 |
+
|
68 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
69 |
+
|
70 |
+
## How to Get Started with the Model
|
71 |
+
|
72 |
+
Use the code below to get started with the model.
|
73 |
+
|
74 |
+
[More Information Needed]
|
75 |
+
|
76 |
+
## Training Details
|
77 |
+
|
78 |
+
### Training Data
|
79 |
+
|
80 |
+
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
81 |
+
|
82 |
+
[More Information Needed]
|
83 |
+
|
84 |
+
### Training Procedure
|
85 |
+
|
86 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
87 |
+
|
88 |
+
#### Preprocessing [optional]
|
89 |
+
|
90 |
+
[More Information Needed]
|
91 |
+
|
92 |
+
|
93 |
+
#### Training Hyperparameters
|
94 |
+
|
95 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
96 |
+
|
97 |
+
#### Speeds, Sizes, Times [optional]
|
98 |
+
|
99 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
100 |
+
|
101 |
+
[More Information Needed]
|
102 |
+
|
103 |
+
## Evaluation
|
104 |
+
|
105 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
106 |
+
|
107 |
+
### Testing Data, Factors & Metrics
|
108 |
+
|
109 |
+
#### Testing Data
|
110 |
+
|
111 |
+
<!-- This should link to a Dataset Card if possible. -->
|
112 |
+
|
113 |
+
[More Information Needed]
|
114 |
+
|
115 |
+
#### Factors
|
116 |
+
|
117 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
118 |
+
|
119 |
+
[More Information Needed]
|
120 |
+
|
121 |
+
#### Metrics
|
122 |
+
|
123 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
124 |
+
|
125 |
+
[More Information Needed]
|
126 |
+
|
127 |
+
### Results
|
128 |
+
|
129 |
+
[More Information Needed]
|
130 |
+
|
131 |
+
#### Summary
|
132 |
+
|
133 |
+
|
134 |
+
|
135 |
+
## Model Examination [optional]
|
136 |
+
|
137 |
+
<!-- Relevant interpretability work for the model goes here -->
|
138 |
+
|
139 |
+
[More Information Needed]
|
140 |
+
|
141 |
+
## Environmental Impact
|
142 |
+
|
143 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
144 |
+
|
145 |
+
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
146 |
+
|
147 |
+
- **Hardware Type:** [More Information Needed]
|
148 |
+
- **Hours used:** [More Information Needed]
|
149 |
+
- **Cloud Provider:** [More Information Needed]
|
150 |
+
- **Compute Region:** [More Information Needed]
|
151 |
+
- **Carbon Emitted:** [More Information Needed]
|
152 |
+
|
153 |
+
## Technical Specifications [optional]
|
154 |
+
|
155 |
+
### Model Architecture and Objective
|
156 |
+
|
157 |
+
[More Information Needed]
|
158 |
+
|
159 |
+
### Compute Infrastructure
|
160 |
+
|
161 |
+
[More Information Needed]
|
162 |
+
|
163 |
+
#### Hardware
|
164 |
+
|
165 |
+
[More Information Needed]
|
166 |
+
|
167 |
+
#### Software
|
168 |
+
|
169 |
+
[More Information Needed]
|
170 |
+
|
171 |
+
## Citation [optional]
|
172 |
+
|
173 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
174 |
+
|
175 |
+
**BibTeX:**
|
176 |
+
|
177 |
+
[More Information Needed]
|
178 |
+
|
179 |
+
**APA:**
|
180 |
+
|
181 |
+
[More Information Needed]
|
182 |
+
|
183 |
+
## Glossary [optional]
|
184 |
+
|
185 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
186 |
+
|
187 |
+
[More Information Needed]
|
188 |
+
|
189 |
+
## More Information [optional]
|
190 |
+
|
191 |
+
[More Information Needed]
|
192 |
+
|
193 |
+
## Model Card Authors [optional]
|
194 |
+
|
195 |
+
[More Information Needed]
|
196 |
+
|
197 |
+
## Model Card Contact
|
198 |
+
|
199 |
+
[More Information Needed]
|
200 |
+
### Framework versions
|
201 |
+
|
202 |
+
- PEFT 0.12.0
|
adapter_config (2).json
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"alpha_pattern": {},
|
3 |
+
"auto_mapping": null,
|
4 |
+
"base_model_name_or_path": "unsloth/meta-llama-3.1-8b-instruct-bnb-4bit",
|
5 |
+
"bias": "none",
|
6 |
+
"fan_in_fan_out": false,
|
7 |
+
"inference_mode": true,
|
8 |
+
"init_lora_weights": true,
|
9 |
+
"layer_replication": null,
|
10 |
+
"layers_pattern": null,
|
11 |
+
"layers_to_transform": null,
|
12 |
+
"loftq_config": {},
|
13 |
+
"lora_alpha": 16,
|
14 |
+
"lora_dropout": 0,
|
15 |
+
"megatron_config": null,
|
16 |
+
"megatron_core": "megatron.core",
|
17 |
+
"modules_to_save": null,
|
18 |
+
"peft_type": "LORA",
|
19 |
+
"r": 16,
|
20 |
+
"rank_pattern": {},
|
21 |
+
"revision": null,
|
22 |
+
"target_modules": [
|
23 |
+
"o_proj",
|
24 |
+
"down_proj",
|
25 |
+
"v_proj",
|
26 |
+
"q_proj",
|
27 |
+
"k_proj",
|
28 |
+
"up_proj",
|
29 |
+
"gate_proj"
|
30 |
+
],
|
31 |
+
"task_type": "CAUSAL_LM",
|
32 |
+
"use_dora": false,
|
33 |
+
"use_rslora": false
|
34 |
+
}
|
special_tokens_map.json
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<|begin_of_text|>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": false,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"eos_token": {
|
10 |
+
"content": "<|eot_id|>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": false,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": {
|
17 |
+
"content": "<|finetune_right_pad_id|>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": false,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
}
|
23 |
+
}
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
training_llama_3_1.py
ADDED
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""Training Llama 3.1.ipynb
|
3 |
+
|
4 |
+
Automatically generated by Colab.
|
5 |
+
|
6 |
+
Original file is located at
|
7 |
+
https://colab.research.google.com/drive/19LthnXISqvXgzE-1S2crf-PtTv3OaRmo
|
8 |
+
|
9 |
+
# **TRAINING DEL MODELO**
|
10 |
+
|
11 |
+
**Instalación de dependencias**
|
12 |
+
"""
|
13 |
+
|
14 |
+
# Commented out IPython magic to ensure Python compatibility.
|
15 |
+
# %%capture
|
16 |
+
# !pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
|
17 |
+
# !pip install --no-deps "xformers<0.0.27" "trl<0.9.0" peft accelerate bitsandbytes
|
18 |
+
# !pip install datasets # Se instalan
|
19 |
+
|
20 |
+
from unsloth import FastLanguageModel # Normalmente se utiliza transformers, pero esta es una librería que permite finetunear rápidamente modelos de lenguaje
|
21 |
+
import torch
|
22 |
+
max_seq_length = 2048 # Se puede elegir cualquier largo. Esta librería permite autoscaling (escala automáticamente si el dataset cuenta con un máximo mayor)
|
23 |
+
dtype = None
|
24 |
+
load_in_4bit = True # Cuantificación 4bit para reducir el uso de memoria
|
25 |
+
|
26 |
+
model, tokenizer = FastLanguageModel.from_pretrained(
|
27 |
+
model_name = "unsloth/Meta-Llama-3.1-8B-Instruct", # Modelo Llama 3.1 pre-entrenado para la respuesta a instrucciones
|
28 |
+
max_seq_length = max_seq_length,
|
29 |
+
dtype = dtype,
|
30 |
+
load_in_4bit = load_in_4bit,
|
31 |
+
)
|
32 |
+
|
33 |
+
"""**Definición de los Lora Adapters**"""
|
34 |
+
|
35 |
+
model = FastLanguageModel.get_peft_model(
|
36 |
+
model,
|
37 |
+
r = 16, # Configura el número de parámetros de rango para LoRA. Se recomienda usar valores como 8, 16, 32, 64, 128.
|
38 |
+
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
|
39 |
+
"gate_proj", "up_proj", "down_proj",],
|
40 |
+
lora_alpha = 16, # Establece el valor de alpha para LoRA. Es un hiperparámetro que controla la intensidad de la adaptación de LoRA.
|
41 |
+
lora_dropout = 0, # Configura la tasa de abandono para LoRA. Se puede usar cualquier valor, pero 0 es la configuración más optimizada.
|
42 |
+
bias = "none", # Determina el tipo de sesgo para LoRA. La opción "none" es la más optimizada y elimina el sesgo en el modelo.
|
43 |
+
# [NUEVO] La opción "unsloth" reduce el uso de VRAM en un 30% y permite tamaños de lote hasta 2 veces mayores.
|
44 |
+
use_gradient_checkpointing = "unsloth", # Usa True o "unsloth" para habilitar el registro de puntos de control de gradientes, lo que es útil para contextos muy largos.
|
45 |
+
random_state = 3407, # Establece la semilla para la generación de números aleatorios, asegurando reproducibilidad en el entrenamiento.
|
46 |
+
use_rslora = False, # Indica si se utiliza LoRA con rango estabilizado, que puede mejorar la estabilidad del entrenamiento.
|
47 |
+
loftq_config = None, # Configura LoftQ si se requiere. LoftQ es una técnica adicional que puede ser utilizada en el modelo.
|
48 |
+
)
|
49 |
+
|
50 |
+
"""**Preparación del dataset**"""
|
51 |
+
|
52 |
+
alpaca_prompt = """Below is an instruction that describes a task, with an input that gives more context. Write a response that appropriately completes the request.
|
53 |
+
|
54 |
+
### Instruction:
|
55 |
+
Below you have a sentence in quotation marks. Provide the syntactic category of each word in the context of the sentence.
|
56 |
+
|
57 |
+
### Sentence:
|
58 |
+
"{}"
|
59 |
+
|
60 |
+
### Response:
|
61 |
+
{}"""
|
62 |
+
|
63 |
+
EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKEN
|
64 |
+
def formatting_prompts_func(examples):
|
65 |
+
length= len(examples["sentence"])
|
66 |
+
sentences = examples["sentence"]
|
67 |
+
tags = examples["sentence_tagged"]
|
68 |
+
texts = []
|
69 |
+
for sentence,tag in zip(sentences,tags):
|
70 |
+
# Must add EOS_TOKEN, otherwise your generation will go on forever!
|
71 |
+
text = alpaca_prompt.format(sentence,tag) + EOS_TOKEN
|
72 |
+
texts.append(text)
|
73 |
+
return { "text" : texts, }
|
74 |
+
pass
|
75 |
+
|
76 |
+
from datasets import load_dataset
|
77 |
+
dataset = load_dataset("manupinasco/syntax_analysis")
|
78 |
+
dataset_train = dataset["train"].map(formatting_prompts_func, batched = True,)
|
79 |
+
dataset_test = dataset["test"]
|
80 |
+
|
81 |
+
"""**Prueba pre-entrenamiento**"""
|
82 |
+
|
83 |
+
FastLanguageModel.for_inference(model) # Enable native 2x faster inference
|
84 |
+
for sentence in dataset_test["sentence"][:5]:
|
85 |
+
inputs = tokenizer(
|
86 |
+
[
|
87 |
+
alpaca_prompt.format(
|
88 |
+
"Below you have a sentence in quotation marks. Provide the syntactic category of each word in the context of the sentence.", # instruction
|
89 |
+
f' "{sentence}" ', # input
|
90 |
+
"", # output - leave this blank for generation!
|
91 |
+
)
|
92 |
+
], return_tensors = "pt").to("cuda")
|
93 |
+
|
94 |
+
outputs = model.generate(**inputs, max_new_tokens = 64, use_cache = True)
|
95 |
+
response = str(tokenizer.batch_decode(outputs))
|
96 |
+
response=response.split("Response:")[1].replace("']", "").replace("\\n", "").replace("<|eot_id|>", "").lstrip()
|
97 |
+
print("INPUT: "+sentence+"/// RESPONSE: "+response)
|
98 |
+
|
99 |
+
"""**Testeo pre-entrenamiento**"""
|
100 |
+
|
101 |
+
total = len(dataset_train["sentence"])
|
102 |
+
correct = 0
|
103 |
+
i=0
|
104 |
+
for sentence in dataset_test["sentence"]:
|
105 |
+
inputs = tokenizer(
|
106 |
+
[
|
107 |
+
alpaca_prompt.format(
|
108 |
+
"Below you have a sentence in quotation marks. Provide the syntactic category of each word in the context of the sentence.", # instruction
|
109 |
+
f' "{sentence}" ', # input
|
110 |
+
"", # output - leave this blank for generation!
|
111 |
+
)
|
112 |
+
], return_tensors = "pt").to("cuda")
|
113 |
+
|
114 |
+
outputs = model.generate(**inputs, max_new_tokens = 64, use_cache = True)
|
115 |
+
response = str(tokenizer.batch_decode(outputs))
|
116 |
+
response=response.split("Response:")[1].replace("']", "").replace("\\n", "").replace("<|eot_id|>", "").lstrip()
|
117 |
+
if response.lower()==dataset_test["sentence_tagged"][i].lower():
|
118 |
+
correct+=1
|
119 |
+
print("RESPONSE: "+response)
|
120 |
+
print("CORRECT_RESPONSE: "+dataset_test["sentence_tagged"][i])
|
121 |
+
print("CORRECT RESPONSES SO FAR: "+correct)
|
122 |
+
print("NUMBER OF SENTENCE: "+i)
|
123 |
+
i+=1
|
124 |
+
|
125 |
+
print("CORRECT "+correct+" OUT OF "+total+". PERCENTAGE "+(correct/total)*100)
|
126 |
+
|
127 |
+
"""**Entrenamiento del modelo**
|
128 |
+
|
129 |
+
|
130 |
+
|
131 |
+
* *Epoch*: cantidad de veces que recorre el dataset completo
|
132 |
+
* *Batch*: cantidad de subgrupos en los que divide al dataset.
|
133 |
+
* Entrenamiento común: cada vez que se recorre un batch, se updatean los weights.
|
134 |
+
* Entrenamiento por **gradient accumulation**: para casos donde se cuente con poca memoria. Sirve para ir acumulando el gradiente de las distintas partes del batch de forma tal de no computar el gradiente recién al finalizarlo.
|
135 |
+
|
136 |
+
* En el caso de gradient accumulation, el batch size es = batch size per device x gradient accumulation steps.
|
137 |
+
|
138 |
+
* *Batch size*: partes en las que realmente dividí al conjunto de datos.
|
139 |
+
|
140 |
+
* *Batch size per device*: partes en las que dividí al conjunto de datos para, al terminar de recorrer cada una de estas partes, hacer un update de los weights.
|
141 |
+
|
142 |
+
* *Gradient accumulation steps*: veces que, por cada batch size per device, acumulé las gradientes previo al update de los weights.
|
143 |
+
|
144 |
+
|
145 |
+
|
146 |
+
|
147 |
+
|
148 |
+
|
149 |
+
|
150 |
+
|
151 |
+
|
152 |
+
|
153 |
+
"""
|
154 |
+
|
155 |
+
from trl import SFTTrainer
|
156 |
+
from transformers import TrainingArguments
|
157 |
+
from unsloth import is_bfloat16_supported
|
158 |
+
|
159 |
+
trainer = SFTTrainer(
|
160 |
+
model = model,
|
161 |
+
tokenizer = tokenizer,
|
162 |
+
train_dataset = dataset_train,
|
163 |
+
dataset_text_field = "text",
|
164 |
+
max_seq_length = max_seq_length,
|
165 |
+
dataset_num_proc = 2,
|
166 |
+
packing = False, # Puede hacer el entrenamiento 5x más rápido para oraciones breves.
|
167 |
+
args = TrainingArguments(
|
168 |
+
per_device_train_batch_size = 2,
|
169 |
+
gradient_accumulation_steps = 4,
|
170 |
+
warmup_steps = 5,
|
171 |
+
# num_train_epochs = 1, # Si se setea a 1 hace una corrida completa por todo el dataset.
|
172 |
+
max_steps = 60,
|
173 |
+
learning_rate = 2e-4,
|
174 |
+
fp16 = not is_bfloat16_supported(),
|
175 |
+
bf16 = is_bfloat16_supported(),
|
176 |
+
logging_steps = 1,
|
177 |
+
optim = "adamw_8bit",
|
178 |
+
weight_decay = 0.01,
|
179 |
+
lr_scheduler_type = "linear",
|
180 |
+
seed = 3407,
|
181 |
+
output_dir = "outputs",
|
182 |
+
),
|
183 |
+
)
|
184 |
+
|
185 |
+
trainer_stats = trainer.train()
|
186 |
+
|
187 |
+
"""# **TESTEO DEL MODELO**
|
188 |
+
|
189 |
+
**Prueba post-entrenamiento**
|
190 |
+
"""
|
191 |
+
|
192 |
+
FastLanguageModel.for_inference(model) # Enable native 2x faster inference
|
193 |
+
for sentence in dataset_test["sentence"][:5]:
|
194 |
+
inputs = tokenizer(
|
195 |
+
[
|
196 |
+
alpaca_prompt.format(
|
197 |
+
f' "{sentence}" ', # input
|
198 |
+
"", # output - leave this blank for generation!
|
199 |
+
)
|
200 |
+
], return_tensors = "pt").to("cuda")
|
201 |
+
|
202 |
+
outputs = model.generate(**inputs, max_new_tokens = 64, use_cache = True)
|
203 |
+
response = str(tokenizer.batch_decode(outputs))
|
204 |
+
response=response.split("Response:")[1].replace("']", "").replace("\\n", "").replace("<|eot_id|>", "").lstrip()
|
205 |
+
print("INPUT: "+sentence+"/// RESPONSE: "+response)
|
206 |
+
|
207 |
+
"""**Testeo post-entrenamiento**"""
|
208 |
+
|
209 |
+
total = len(dataset_train["sentence"])
|
210 |
+
correct = 0
|
211 |
+
i=0
|
212 |
+
for sentence in dataset_test["sentence"]:
|
213 |
+
inputs = tokenizer(
|
214 |
+
[
|
215 |
+
alpaca_prompt.format(
|
216 |
+
f' "{sentence}" ', # input
|
217 |
+
"", # output - leave this blank for generation!
|
218 |
+
)
|
219 |
+
], return_tensors = "pt").to("cuda")
|
220 |
+
|
221 |
+
outputs = model.generate(**inputs, max_new_tokens = 64, use_cache = True)
|
222 |
+
response = str(tokenizer.batch_decode(outputs))
|
223 |
+
response=response.split("Response:")[1].replace("']", "").replace("\\n", "").replace("<|eot_id|>", "").lstrip()
|
224 |
+
if response.lower()==dataset_test["sentence_tagged"][i].lower():
|
225 |
+
correct+=1
|
226 |
+
print("RESPONSE: "+response)
|
227 |
+
print("CORRECT_RESPONSE: "+dataset_test["sentence_tagged"][i])
|
228 |
+
print("CORRECT RESPONSES SO FAR: "+correct)
|
229 |
+
print("NUMBER OF SENTENCE: "+i)
|
230 |
+
i+=1
|
231 |
+
|
232 |
+
print("CORRECT "+correct+" OUT OF "+total+". PERCENTAGE "+(correct/total)*100)
|