IIC
/

Text Generation
Transformers
Safetensors
Spanish
qwen2
chat
conversational
text-generation-inference
Inference Endpoints
File size: 12,590 Bytes
dfd3db0
 
82acfb0
 
 
 
 
dd12671
 
77af4c3
 
 
dfd3db0
 
82acfb0
dfd3db0
2276773
dfd3db0
fcbc4e6
22973fd
dfd3db0
 
 
 
93b673d
dfd3db0
93b673d
dfd3db0
93b673d
 
 
dfd3db0
85fbd11
dfd3db0
93b673d
 
85fbd11
dd12671
93b673d
dfd3db0
93b673d
dfd3db0
47c08d8
dfd3db0
1df3f59
 
 
 
7b015ac
1df3f59
 
 
7b015ac
1df3f59
7b015ac
 
1df3f59
7b015ac
1df3f59
7b015ac
1df3f59
7b015ac
 
 
1df3f59
 
 
7b015ac
1df3f59
93b673d
dfd3db0
5c95c1d
 
ae5a50d
dfd3db0
93b673d
 
 
 
 
 
dfd3db0
bb22957
dfd3db0
93b673d
 
 
 
 
 
 
 
e229229
bb22957
 
 
 
 
 
 
e229229
bb22957
 
 
 
 
e229229
bb22957
 
 
 
 
e229229
bb22957
 
 
 
 
 
 
dfd3db0
9d9086c
 
bb22957
dfd3db0
ec63799
937a31e
ec63799
e229229
ec63799
 
8e315de
937a31e
ec63799
e229229
ec63799
e229229
ec63799
 
937a31e
ec63799
 
 
 
 
937a31e
ec63799
 
 
 
 
 
e229229
ec63799
 
 
 
 
 
 
 
9d9086c
b052992
dfd3db0
 
 
 
1e791b6
dfd3db0
 
 
91f7ce1
dfd3db0
 
 
9ca6703
66d307e
9ca6703
 
ade8595
b052992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85fbd11
 
b052992
 
 
 
 
 
 
 
dfd3db0
9ca6703
 
 
85fbd11
dfd3db0
85fbd11
dfd3db0
85fbd11
 
 
 
 
 
 
dfd3db0
 
 
1e791b6
 
 
 
 
dfd3db0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d1acbf
dfd3db0
 
 
8d1acbf
 
 
 
 
 
 
 
 
 
 
dfd3db0
85fbd11
dfd3db0
85fbd11
 
 
01d9553
85fbd11
 
 
 
 
 
dfd3db0
 
 
8d1acbf
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
---
library_name: transformers
language:
- es
base_model:
- Qwen/Qwen2.5-7B-Instruct
pipeline_tag: text-generation
license: other
license_name: rigochat-2-nc
license_link: https://huggingface.co/IIC/RigoChat-7b-v2/blob/main/LICENSE
tags:
- chat
---

# Model Card for RigoChat-7b-v2

RigoChat-7b-v2 is a Qwen-2.5-based model specifically designed to provide accurate responses from Spanish queries. Specifically, is based on the [Qwen/Qwen2.5-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-7B-Instruct) model and has been fine-tuned with Direct Preference Optimization ([DPO](https://arxiv.org/pdf/2305.18290)) for improved performance in Spanish language.

This model is licensed for **non-commercial use**. If you want to use it commercially, please contact us or use it through the service we offer from the [AWS Marketplace](https://github.com/iiconocimiento/iic-aws/tree/main/notebooks/rigochat-v2).

## Model Details

### Model Description

This model is the second version of RigoChat, a family of Large Language Models (LLMs) designed to solve typical NLP tasks with Spanish instructions such as: Tool Use, Summarization, Math, Code, Abstractive-QA, etc. Like [Qwen/Qwen2.5-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-7B-Instruct), this model has no specific use case and can be applied to a wide range of tasks. Indeed, it offers a slight improvement for generalist tasks in Spanish, particularly in RAG (Retriever Augmented Generation) systems with Spanish databases, as its training focused on resolving questions about contexts to prevent hallucinations and ensure safety responses.

Key benefits of this model include:

- Improved performance on generalist tasks in Spanish.
- Enhanced safety and reduced hallucinations in RAG systems with Spanish texts.
- Possibility of using it in different hardware requirements, especially those with reduced computational capacity. For more information on how to use RigoChat-7b-v2 on reduced hardware, see [IIC/RigoChat-7b-v2-GGUF](https://huggingface.co/IIC/RigoChat-7b-v2-GGUF).

Remarkably, this model was trained on a single A100 GPU with limited computational resources, yet achieved its current state in a relatively short time (8.5 hours). This feat was made possible by leveraging a high-quality dataset and employing advanced techniques such as [LoRA](https://arxiv.org/pdf/2106.09685) to optimize memory usage. Further details on the training process can be found below.

- **Developed by:** Instituto de Ingeniería del Conocimiento (IIC).
- **Model type:** Generative Fine-tuned Transformer.
- **Language(s) (NLP):** Spanish (BCP-47 es).
- **License:** RIGOCHAT 2 NON-COMMERCIAL.
- **Finetuned from model:** [Qwen/Qwen2.5-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-7B-Instruct).

### Model Sources

- **Paper:** **Cooming soon**.

## Uses

### Direct Use

You can use and deploy RigoChat-v2 for commercial purposes through a model package from AWS Marketplace. You can check the instructions inside the [following notebook](https://github.com/iiconocimiento/iic-aws/tree/main/notebooks/rigochat-v2).

### Out-of-Scope Use

This language model has been adapted for general natural language processing tasks in Spanish and specific use cases such as RAG. However, there are several cases where the model should not be used due to its technical and ethical limitations:

- **Illegal Activities:** The model should not be used to generate content related to illegal activities, such as creating malicious software, fraud, incitement to crime, or any illegal material.
- **Harmful or Dangerous Content:** It should not be used to generate hate speech, violence, harassment, or any content that promotes discrimination, violence, or abuse.

### Bias, Risks, and Limitations

Although this model has been trained to understand and generate text in Spanish, there are several risks, biases, and limitations that users should be aware of:

- **Biases:** The model may reflect biases present in the training data. These biases could be related to gender, race, social class, sexual orientation, among others, and may generate responses that perpetuate stereotypes or discrimination.
- **Accuracy and Reliability:** While the model generates coherent and useful text in many contexts, it may not always be 100% accurate or reliable, especially in technical, scientific, or legal matters where high certainty is required.
- **Limited or Outdated Knowledge:** The model is not trained with information beyond its training cutoff date. Therefore, it may not reflect recent events, research, or advancements.

### Recommendations

We recommend using this model as a general chatbot or within applications designed for specific tasks, such as SQL queries, RAG systems, or as an autonomous agent to facilitate the use of tools.

## How to Get Started with the Model

As [Qwen/Qwen2.5-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-7B-Instruct) or any model that uses the `chatml` template.

### To load the model and tokenizer

```python
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
)
import torch

model_name = "IIC/RigoChat-7b-v2"

model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype=torch.bfloat16,
    device_map="cuda",
    trust_remote_code=True,
)
tokenizer = AutoTokenizer.from_pretrained(
    model_name,
    trust_remote_code=True,
)
```

### Sample generation

```python
messages = [
    {"role": "user", "content": "¿Cómo puedo transformar un diccionario de listas en una lista de diccionarios, y viceversa, en Python sin utilizar bucles for?"}
]

text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True,
)
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)

generated_ids = model.generate(
    **model_inputs,
    max_new_tokens=1024,
)
generated_ids = [
    output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]

response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
```

For a better experience, we recommend to use [the following generation parameters](https://huggingface.co/IIC/RigoChat-7b-v2/blob/main/generation_config.json).

### Tool Use

```python
def get_current_weather(location: str, date: str) -> float:
    """
    Obtener la datos del tiempo de una localización.
    
    Args:
        location: La locaización, con el siguiente formato: "Ciudad, País."
        date: La fecha, en el formato AAAA-MM-DD.
    Returns:
        El tiempo en dicha localización.
    """
    return {"temperatura": 22, "cielo": "nublado", "probabilidad de lluvias": "60%"}

messages = [
  {"role": "user", "content": "Este fin de semana quiero visitar Madrid, y no se qué ropa llevarme. ¿Podrías decirme qué tal va a hacer? Es el puente del 6 de diciembre de 2024."}
]

text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    tools=[get_current_weather],
    add_generation_prompt=True
)
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)

generated_ids = model.generate(
    **model_inputs,
    max_new_tokens=1024
)
generated_ids = [
    output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]

response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
```

Check the [tool use documentation](https://huggingface.co/docs/transformers/main/chat_templating#advanced-tool-use--function-calling) from HuggingFace for more information.

## Training Details

### Training Data

A combination of both public and private datasets designed in the IIC. The dataset consists of 21975 conversations in Spanish, with the format `chatml` and has the same structure as the [Anthropic/hh-rlhf dataset](https://huggingface.co/datasets/Anthropic/hh-rlhf). Each conversation has two variants: `chosen` and `rejected`, and only differs the last answer of the assistant. The last answer in the `chosen` variant is considered a better answer than the one in the `rejected` variant. Different techniques have been used to generate the dataset, which we explain in depth in the research (**coming soon**).

### Training Procedure

We use the [Transformer Reinforcement Learning](https://huggingface.co/docs/trl/index) (TRL) library. Specifically, we have applied [the script they have published](https://github.com/huggingface/trl/blob/main/examples/scripts/dpo.py) as an example for using DPO to the dataset we have generated.

#### Training Hyperparameters


<details><summary>Details</summary>
<p>
  
```python
LORA_CONFIG = {
    "r": 64,
    "lora_alpha": 16,
    "lora_dropout": 0.1,
    "bias": "none",
    "task_type": "CAUSAL_LM",
    "target_modules": [
        "q_proj",
        "k_proj",
        "v_proj",
        "o_proj",
        "up_proj",
        "gate_proj",
        "down_proj",
    ],
    "use_rslora": True,
}

DPO_CONFIG = {
    "num_train_epochs": 2,
    "logging_steps": 25,
    "eval_steps": 500,
    "save_steps": 100,
    "save_total_limit": 5,
    "per_device_train_batch_size": 1,
    "per_device_eval_batch_size": 1,
    "gradient_accumulation_steps": 16,
    "learning_rate": 5e-6,
    "max_length": 8192, # max length in the history chat + latest assistant response.
    "max_prompt_length": 6656, # max length in the history chat: user-assistant-...-assistant-user.
    "gradient_checkpointing": True,
    "weight_decay": 0.001,
    "optim": "rmsprop",
    "evaluation_strategy": "steps",
    "lr_scheduler_type": "cosine",
    "bf16": True,
}
```

</p>
</details>

#### Speeds, Sizes, Times

Below are some useful parameters showing the results of the latest training logs.

```python
latest_logs = {'loss': 0.3716, 'grad_norm': 4.989994049072266, 'learning_rate': 1.0380020311950844e-10, 'rewards/chosen': 0.534086287021637, 'rewards/rejected': -0.6236276030540466, 'rewards/accuracies': 0.8899999856948853, 'rewards/margins': 1.1577140092849731, 'logps/rejected': -218.88198852539062, 'logps/chosen': -250.0700225830078, 'logits/rejected': -1.6214849948883057, 'logits/chosen': -1.9585875272750854, 'epoch': 1.99}

final_training_results = {'train_runtime': 30825.7138, 'train_samples_per_second': 1.432, 'train_steps_per_second': 0.089, 'train_loss': 0.483570138469306, 'epoch': 2.0}
```

As can be seen in the time used, in eight and a half hours we have managed to improve a state-of-the-art model, with very little hardware, in tasks adapted to Spanish. This can be seen in more detail in the following sections.

## Evaluation

To evaluate, we use the following datasets:

1. [IIC/AQuAS](https://huggingface.co/datasets/IIC/AQuAS).
2. [IIC/RagQuAS](https://huggingface.co/datasets/IIC/RagQuAS).
3. privados

### Testing Data, Factors & Metrics

#### Testing Data

<!-- This should link to a Dataset Card if possible. -->

[More Information Needed]

#### Factors

<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->

[More Information Needed]

#### Metrics

<!-- These are the evaluation metrics being used, ideally with a description of why. -->

[More Information Needed]

### Results

[More Information Needed]

#### Summary



## Environmental Impact

<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->

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).

- **Hardware Type:** [More Information Needed]
- **Hours used:** [More Information Needed]
- **Cloud Provider:** [More Information Needed]
- **Compute Region:** [More Information Needed]
- **Carbon Emitted:** [More Information Needed]

### Model Architecture and Objective

[More Information Needed]

### Compute Infrastructure

[More Information Needed]

#### Hardware

GPU NVIDIA A100 with Tensor Core.

#### Software

`Ubuntu 22.04.5 LTS` and the following requirements:

```
python=3.11
flash_attn>=2.5.8
datasets
numpy
trl
peft
huggingface_hub
```

## Citation

```
@misc {Instituto de Ingeniería del Conocimiento (IIC),
	author       = { {Instituto de Ingeniería del Conocimiento} },
	title        = { Adapting a language model to Spanish using a bounded dataset and reduced hardware },
	year         = 2024,
	url          = { https://huggingface.co/datasets/IIC/RigoChat-7b-v2 },
	doi          = { 10.57967/hf/2043 },
	publisher    = { Hugging Face }
}
```

## Model Card Contact

- [[email protected]]([email protected]).