ai-forever / ai-forever/MERA

Как добавить форматирование промпта?

Ouverte
#4 2 commentaires 0 réactions 0 personnes assignées Voir sur GitHub
good first issue
Langage dominant
Jupyter Notebook
Étoiles
63
Forks
8
Métriques de merge des PR
Aucune PR mergée en 30 j

Description

Как добавить форматирование промпта для модели?

Некоторые модели тренируются с определенным шаблоном промпта. Например возьмем модель [Open-Orca/Mistral-7B-OpenOrca](https://huggingface.co/Open-Orca/Mistral-7B-OpenOrca).

Данная модель ожидает промпт следующего формата:

```text
<|im_start|>system
You are MistralOrca, a large language model trained by Alignment Lab AI. Write out your reasoning step-by-step to be sure you get the right answers!
<|im_end|>
<|im_start|>user
How are you?<|im_end|>
<|im_start|>assistant
I am doing well!<|im_end|>
<|im_start|>user
Please tell me about how mistral winds have attracted super-orcas.<|im_end|>
<|im_start|>assistant
```

Если подать в модель промпт другого формата, ответ будет **существенно** отличаться. Ниже приведен сниппет кода для воспроизведения.

```python
import os

os.environ["CUDA_VISIBLE_DEVICES"] = "0"

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig

device = "cuda"
model = AutoModelForCausalLM.from_pretrained(
"Open-Orca/Mistral-7B-OpenOrca",
torch_dtype=torch.float16,
device_map={"": 0},
)
tokenizer = AutoTokenizer.from_pretrained("Open-Orca/Mistral-7B-OpenOrca")

generation_config = GenerationConfig(
max_length=256,
temperature=1.1,
top_p=0.95,
repetition_penalty=1.0,
# do_sample=True,
use_cache=True,
eos_token_id=tokenizer.eos_token_id,
pad_token_id=tokenizer.eos_token_id,
)

generation_config = GenerationConfig(
max_length=256,
temperature=1.1,
top_p=0.95,
repetition_penalty=1.0,
# do_sample=True,
use_cache=True,
eos_token_id=tokenizer.eos_token_id,
pad_token_id=tokenizer.eos_token_id,
)

def generate_original_orca(instruction):
chat = [
{"role": "user", "content": instruction},
]
chat = tokenizer.apply_chat_template(
chat, tokenize=False, add_generation_prompt=True
)
print(chat)

inputs = tokenizer(chat, return_tensors="pt").to(device)
outputs = model.generate(**inputs, generation_config=generation_config)[0]
outputs = outputs[len(inputs["input_ids"][0]) :]
text = tokenizer.decode(outputs)
text = text.replace("<|im_end|>", "").strip()
return text

def generate_original_orca_no_template(instruction):
inputs = tokenizer(instruction, return_tensors="pt").to(device)
outputs = model.generate(**inputs, generation_config=generation_config)[0]
outputs = outputs[len(inputs["input_ids"]) :]
text = tokenizer.decode(outputs)
text = text.strip()
return text

print("CHAT TEMPLATE")
print(generate_original_orca("Почему трава зеленая?"))
print("NO TEMPLATE")
print(generate_original_orca_no_template("Почему трава зеленая?"))

```
```text
CHAT TEMPLATE
<|im_start|>user
Почему трава зеленая?<|im_end|>
<|im_start|>assistant

Зеленой окраской у растений обуславливается наличие хлорофилла, который является основным пигментом, отвечающим за процесс фотосинтеза. Фотосинтез - это процесс, благодаря которому растения превращают свет, углекислый газ и воду в углеводы и кислород. Хлорофилл поглощает свет, в основном в зелёном диапазоне, и превращает его в энергию, необходимую для синтеза углеводов. Таким образом, зеленая окраска растений обусловлена наличием хлорофилла и процессом фотосинтеза, который обеспечивает их рост и развитие.
NO TEMPLATE
Почему трава зеленая?

The question "Почему трава зеленая?" translates to "Why is the grass green?" in English. This question is often asked by children who are curious about the colors they see in nature.

The color green is associated with grass, leaves, and other plants because of the presence of chlorophyll, a pigment that is responsible for the process of photosynthesis. Photosynthesis is the process by which plants, algae, and some bacteria convert light energy into chemical energy in the form of glucose. This process is essential for the growth and survival of plants, as it allows them to produce their own food using sunlight, water, and carbon dioxide.

Chlorophyll is a green pigment because it absorbs light most efficiently in the blue and red parts of the spectrum, while reflecting green light. This is why plants appear green to our eyes. The other colors we see in plants, such as red, orange, and yellow, are due to the presence of other pigments called carotenoids and anthocyanins. These pigments are responsible for the vibrant colors we see in
```

Guide de contribution

Aucun guide de contribution indexé pour ce dépôt

Évaluation

Cette issue n'a pas encore été évaluée.

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.