File size: 9,880 Bytes
733f242
 
 
 
 
 
 
 
 
88ca543
386777f
 
733f242
386777f
733f242
 
6c5b030
 
8b153e0
d527604
491d563
 
d527604
 
6c5b030
 
c946b2e
6c5b030
 
 
8133f1e
6c5b030
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05ba9f1
6c5b030
 
05ba9f1
6c5b030
 
05ba9f1
6c5b030
 
 
05ba9f1
6c5b030
 
05ba9f1
6c5b030
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05ba9f1
6c5b030
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
491d563
6c5b030
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
---
language:
- pt
license: cc-by-4.0
tags:
- peft
- LoRA
- Llama
- Stanford-Alpaca
datasets:
- dominguesm/alpaca-data-pt-br
thumbnail: https://huggingface.co/dominguesm/alpaca-lora-ptbr-7b/resolve/main/assets/alpaca_br_juliet_2.jpg
inference: false
base_model: decapoda-research/llama-7b-hf
---

## 🦙🇧🇷 Alpaca-LoRA-PTBR: Low-Rank LLaMA Instruct-Tuning

<a target="_blank" href="https://colab.research.google.com/github/DominguesM/alpaca-lora-ptbr-7b/blob/main/notebooks/02%20-%20Evaluate.ipynb">
  <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
</a><a target="_blank" href="https://github.com/DominguesM/alpaca-lora-ptbr-7b">
  <img src="https://img.shields.io/badge/-Github-blue?style=social&logo=github&link=https://github.com/DominguesM/alpaca-lora-ptbr-7b" alt="Github Project Page"/>
</a>

</br>

<img align="left" style="margin-right: 20px;" height="120" src="https://huggingface.co/dominguesm/alpaca-lora-ptbr-7b/resolve/main/assets/alpaca_br_juliet_2.jpg">

**This model was trained and made available solely and exclusively for research purposes.**

Try the pretrained model out on Colab [here](https://colab.research.google.com/github/DominguesM/alpaca-lora-ptbr-7b/blob/main/notebooks/02%20-%20Evaluate.ipynb)!

This repository contains a [low-ranked adapter (LoRa)](https://arxiv.org/pdf/2106.09685.pdf) for LLaMA-7b fit on the [**Stanford Alpaca dataset**](https://github.com/tatsu-lab/stanford_alpaca) translated into **Brazilian Portuguese** using the [**Helsinki-NLP/opus-mt-tc-big-en-pt**](https://huggingface.co/Helsinki-NLP/opus-mt-tc-big-en-pt) model.

As the foundation model has not yet been made openly available by **Meta** [(request form)](https://docs.google.com/forms/d/e/1FAIpQLSfqNECQnMkycAp2jP4Z9TFX0cGR4uf7b_fBxjY_OjhJILlKGA/viewform), it is not included in this repository, but you can easily find them by searching on Github or here on HuggingFace. </br> </br>

## Inference

```python
!pip install -q loralib
!pip install -q sentencepiece
!pip install -q bitsandbytes
!pip install -q git+https://github.com/huggingface/transformers.git
!pip install -q git+https://github.com/huggingface/peft.git

from peft import PeftModel
from transformers import LlamaForCausalLM, LlamaTokenizer, GenerationConfig

llama_7b_hf_model_id = ""

tokenizer = LlamaTokenizer.from_pretrained(llama_7b_hf_model_id)
model = LlamaForCausalLM.from_pretrained(
    llama_7b_hf_model_id,
    load_in_8bit=True,
    device_map="auto",
)
model = PeftModel.from_pretrained(model, "dominguesm/alpaca-lora-ptbr-7b")

def generate_prompt(instruction, input=None):
    if input:
        return f"""Abaixo está uma instrução que descreve uma tarefa, emparelhada com uma entrada que fornece mais contexto. Escreva uma resposta que conclua adequadamente a solicitação.

### Instruções:
{instruction}

### Entrada:
{input}

### Resposta:"""
    else:
        return f"""Abaixo está uma instrução que descreve uma tarefa. Escreva uma resposta que conclua adequadamente a solicitação.

### Instruções:
{instruction}

### Resposta:"""

generation_config = GenerationConfig(
    temperature=0.1,
    top_p=0.75,
    num_beams=4,
)

def generate(instruction, input=None):
    prompt = generate_prompt(instruction, input)
    inputs = tokenizer(prompt, return_tensors="pt")
    input_ids = inputs["input_ids"].cuda()
    generation_output = model.generate(
        input_ids=input_ids,
        generation_config=generation_config,
        return_dict_in_generate=True,
        output_scores=True,
        max_new_tokens=512
    )
    for s in generation_output.sequences:
        output = tokenizer.decode(s)
        print("Resposta:", output.split("### Resposta:")[1].strip())

generate(input("Instrução: "))

```

## Example outputs

```
Instruções (Instruction): Me fale sobre alpacas

Alpaca-LoRA-PTBR: 'Alpacas são uma espécie de camelo nativa da América do Sul. Eles '
'são conhecidos por serem pacíficos e tranquilos, e muitas vezes são mantidos '
'como animais de estimação domésticos. Alpacas são conhecidas por seus longos '
'e finos cabelos, que podem ser usados para fazer roupas e cobertores. Eles '
'também podem ser usados para produzir leite e carne.

```

```
Instruções (Instruction): Me explique sobre o que é a Lei Maria da Penha do Brasil.

Alpaca-LoRA-PTBR: 'A Lei Maria da Penha do Brasil é uma lei brasileira que proíbe a '
 'discriminação e a violência contra as mulheres. A lei foi nomeada em '
 'homenagem a Maria da Penha, uma mulher que foi assassinada em 1973 por seu '
 'ex-namorado. A lei foi aprovada em 1985 e proíbe a discriminação e a '
 'violência contra as mulheres. A lei proíbe a discriminação e a violência '
 'contra as mulheres, incluindo a discriminação e a violência de gênero, a '
 'discriminação e a violência sexual, a discriminação e a violência econômica, '
 'a discriminação e a violência física e a discriminação e a violência '
 'psicológica.'


In this case the model missed the following points:

* Maria da Penha Fernandes was not murdered, but suffered an attempted murder.
* Maria da Penha Fernandes is alive.
* The attempted homicide took place in 1983.
* The law was sanctioned in 2006.
```

```
Instruções (Instruction): Dada a fórmula química, calcule a massa molar.

Entrada (Input): CaCl2

Alpaca-LoRA-PTBR: 'A massa molar de cloreto de cálcio é 110,98 g/mol.'

```

```
Instruções (Instruction): Faça quatro perguntas sobre a seguinte passagem:

Entrada (Input): A anatomia de uma abelha é bastante intrincada. Tem três partes do corpo: a cabeça, o tórax e o abdômen. A cabeça consiste em órgãos sensoriais, três olhos simples e dois olhos compostos e vários apêndices. O tórax tem três pares de pernas e dois pares de asas, enquanto o abdômen contém a maioria dos órgãos da abelha, incluindo o sistema reprodutivo e o sistema digestivo.

Alpaca-LoRA-PTBR: '1. Quais são os órgãos sensoriais da cabeça da abelha? 2. Quais '
 'são os órgãos sensoriais do tórax da abelha? 3. Quais são os órgãos '
 'sensoriais do abdômen da abelha? 4. Quais são os órgãos do sistema '
 'reprodutivo da abelha?'

```

```
Instruções (Instruction): Analise o documento jurídico fornecido e explique os pontos-chave.

Entrada (Input): O seguinte é um trecho de um contrato entre duas partes, rotulado como "Empresa A" e "Empresa B": "A Empresa A concorda em fornecer assistência razoável à Empresa B para garantir a precisão das demonstrações financeiras que fornece. Isso inclui permitir à Empresa um acesso razoável ao pessoal e outros documentos que possam ser necessários para a revisão da Empresa B. A Empresa B concorda em manter o documento fornecido pela Empresa A em confiança e não divulgará as informações a terceiros sem a permissão explícita da Empresa A".

Alpaca-LoRA-PTBR: 'Este documento é um contrato entre duas partes, rotulado como '
 '"Empresa A" e "Empresa B". A Empresa A concorda em fornecer assistência '
 'razoável à Empresa B para garantir a precisão das demonstrações financeiras '
 'que fornece. Isso inclui permitir à Empresa um acesso razoável ao pessoal e '
 'outros documentos que possam ser necessários para a revisão da Empresa B. A '
 'Empresa B concorda em manter o documento fornecido pela Empresa A em '
 'confiança e não divulgará as informações a terceiros sem a permissão '
 'explícita da Empresa A.''

```

##  Training procedure

Fine-tuning was done via the Trainer API. Here is the [Jupyter notebook](https://colab.research.google.com/github/DominguesM/alpaca-lora-ptbr-7b/blob/main/notebooks/02%20-%20Train%20Model%20LoRa.ipynb) with the training code.

### Training hyperparameters

The following hyperparameters were used during training:

| Hyperparameter | Value |
|----------------|-------|
| Batch size     | 128   |
| Learning rate  | 3e-5  |
| Epochs         | 3     |
| Max length     | 512   |
| Lora R         | 8     |
| Lora Alpha     | 16    |
| Lora Dropout   | 0.5   |

### Training results 

The validation results on the valid split are summarised here below.

|Step |	Training Loss |	Validation Loss|
|-----|---------------|----------------|
|200 |	0.891900 |	0.891723|
|400 |	0.854400 |	0.866401|
|600 |	0.850600 |	0.854273|
|800 |	0.831000 |	0.846825|
|1000 |	0.832000 |	0.842221|

## Ethical considerations ([LLaMA Model Card](https://github.com/facebookresearch/llama))

**Data**
The data used to train the model is collected from various sources, mostly from the Web. As such, it contains offensive, harmful and biased content. We thus expect the model to exhibit such biases from the training data.

**Human life**
The model is not intended to inform decisions about matters central to human life, and should not be used in such a way.

**Mitigations**
We filtered the data from the Web based on its proximity to Wikipedia text and references. For this, we used a Kneser-Ney language model and a fastText linear classifier.

**Risks and harms**
Risks and harms of large language models include the generation of harmful, offensive or biased content. These models are often prone to generating incorrect information, sometimes referred to as hallucinations. We do not expect our model to be an exception in this regard.

**Use cases**
LLaMA is a foundational model, and as such, it should not be used for downstream applications without further investigation and mitigations of risks. These risks and potential fraught use cases include, but are not limited to: generation of misinformation and generation of harmful, biased or offensive content.

## References

* Workout descriptions and script based on work done by [Eric J. Wang](https://github.com/tloen/alpaca-lora)
* Training data based on original [Stanford Alpaca](https://crfm.stanford.edu/2023/03/13/alpaca.html) work