File size: 5,612 Bytes
baecc58
 
c3bbe74
 
 
 
 
 
052e817
 
baecc58
c3bbe74
 
 
 
 
 
 
 
 
 
880ce9c
c3bbe74
0c49286
c3bbe74
 
0c49286
c3bbe74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7bee59
c3bbe74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b181673
 
c3bbe74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
---
license: openrail
datasets:
- bertin-project/alpaca-spanish
library_name: peft
language:
- es
pipeline_tag: text-generation
tags:
- alpaca
---

# BERTIN-GPT-J-6B Alpaca

This is a [BERTIN GPT-J-6B](https://huggingface.co/bertin-project/bertin-gpt-j-6B) Spanish model fine-tuned on the [Spanish Alpaca](https://huggingface.co/datasets/bertin-project/alpaca-spanish) dataset.

## Usage

```python
from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig, pipeline

base_model = "bertin-project/bertin-gpt-j-6B-alpaca"
tokenizer = AutoTokenizer.from_pretrained(base_model)
model = AutoModelForCausalLM.from_pretrained(base_model)
```

For generation, we can either use `pipeline()` or the model's `.generate()` method. Remember that the prompt needs a **Spanish** template:

```python
# Generate responses
def generate(instruction, input=None):
    if input:
        prompt = f"""A continuación hay una instrucción que describe una tarea, junto con una entrada que proporciona más contexto. Escribe una respuesta que complete adecuadamente lo que se pide.

### Instrucción:
{instruction}

### Entrada:
{input}

### Respuesta:"""
    else:
        prompt = f""""A continuación hay una instrucción que describe una tarea. Escribe una respuesta que complete adecuadamente lo que se pide.

### Instrucción:
{instruction}

### Respuesta:
"""
    inputs = tokenizer(prompt, return_tensors="pt")
    input_ids = inputs["input_ids"].cuda()
    generation_output = model.generate(
        input_ids=input_ids,
        generation_config=GenerationConfig(temperature=0.2, top_p=0.75, num_beams=4),
        return_dict_in_generate=True,
        output_scores=True,
        max_new_tokens=256
    )
    for seq in generation_output.sequences:
        output = tokenizer.decode(seq, skip_special_tokens)
        print(output.split("### Respuesta:")[-1].strip())

generate("Escribe un correo electrónico dando la bienvenida a un nuevo empleado llamado Manolo.")
# Estimado Manolo,
#
# ¡Bienvenido a nuestro equipo! Estamos muy contentos de que hayas decidido unirse a nosotros y estamos ansiosos por comenzar a trabajar juntos. 
#
# Nos gustaría darte las gracias por tu interés en nuestro equipo y esperamos que tengas un gran tiempo aquí. 
#
# Si tienes alguna pregunta o duda, no dudes en contactarnos. 
#
# Atentamente, 
# Equipo de [Nombre del Departamento]
```


## Data

The dataset is a translation to Spanish of [alpaca_data_cleaned.json](https://github.com/tloen/alpaca-lora/blob/main/alpaca_data_cleaned.json) (a clean version of the [Alpaca dataset made at Stanford](https://huggingface.co/datasets/tatsu-lab/alpaca)) using OpenAI's `gpt-3.5-turbo` model. We translated using a full-sample prompt instead of per strings, which resulted in more coherent tuples of `(instruction, input, output)` and costed around $60.0.

**This dataset cannot be used to create models that compete in any way with OpenAI.**

## Finetuning

To fine-tune the BERTIN GPT-J-6B model we used the code available on [BERTIN's fork of `mesh-transformer-jax`](https://github.com/bertin-project/mesh-transformer-jax/blob/master/prepare_dataset_alpaca.py), which provides code adapt an Alpaca dataset to finetune any GPT-J-6B model. We run finetuning for 3 epochs using sequence length of 2048 with no gradient accumulation on a single TPUv3-8 for 3 hours on top of BERTIN GPT-J-6B.

## Example outputs

Stanford Alpaca:
```
Instruction: Inventa una excusa creativa para decir que no tengo que ir a la fiesta.
Response: I'm sorry, I can't make it to the party. I have to stay home and take care of my sick pet.
```

BERTIN Alpaca LoRA:
```
Instruction: Inventa una excusa creativa para decir que no tengo que ir a la fiesta.
Response: No puedo ir a la fiesta porque tengo que terminar un proyecto urgente.
```


Stanford Alpaca:
```
Instruction: ¿Cómo puedo comenzar una carrera como científico de datos? Responde con una lista de pasos a seguir.
Response: To begin a career as a data scientist, there are a few steps to take. First, you should have a bachelor's degree in a STEM-related field, such as computer science, mathematics, statistics, or engineering. You should also have experience with programming languages such as Python, R, or Java. Additionally, it is helpful to have knowledge of machine learning, data visualization, and data analytics. Finally, it is important to stay up to date with the latest trends and technologies in the field.
```

BERTIN Alpaca LoRA:
```
Instruction: ¿Cómo puedo comenzar una carrera como científico de datos? Responde con una lista de pasos a seguir.
Response: Para comenzar una carrera como científico de datos, hay varios pasos a seguir. Primero, obtener una licenciatura en matemáticas, informática o ciencias de la computación. Luego, obtener una maestría o doctorado en ciencias de la computación, informática o alguna otra área relacionada. Finalmente, obtener experiencia en el campo trabajando en proyectos de investigación o desarrollando aplicaciones.

```

You can test it using the eval notebook [here](https://colab.research.google.com/github/22-hours/cabrita/blob/main/notebooks/cabrita-lora.ipynb).

## References

- [LLaMA](https://ai.facebook.com/blog/large-language-model-llama-meta-ai/)
- [Stanford Alpaca](https://github.com/tatsu-lab/stanford_alpaca)
- [BERTIN Alpaca](https://huggingface.co/datasets/bertin-project/alpaca-spanish)
- [ChatGPT](https://openai.com/blog/chatgpt)
- [Hugging Face](https://huggingface.co/)
 
## Hardware Requirements

For training we have used a Google Cloud TPUv3-8 VM. For eval, you can use a T4.