ai-forever / MERA

MERA (Multimodal Evaluation for Russian-language Architectures) is a new open benchmark for the Russian language for evaluating fundamental models.
MIT License
49 stars 8 forks source link

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

Open dmitrymailk opened 7 months ago

dmitrymailk commented 7 months ago

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

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

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

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

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

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("Почему трава зеленая?"))
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
LSinev commented 7 months ago

Тут всё уникально, поэтому мы не стали никак фиксировать на данном этапе.

Надеемся получить различные сабмиты моделей, чтобы далее, учитывая разнообразие, предложить некоторый вариант общий, как это встраивать и логировать. Будем рады вашим pull request.

Можно посмотреть в сторону правок в этой части: https://github.com/ai-forever/MERA/blob/main/lm-evaluation-harness/lm_eval/base.py#L714 (параметр description).

LSinev commented 1 month ago

В экспериментальной ветке https://github.com/ai-forever/MERA/tree/update/new_harness_codebase со свежим кодом из lm-evaluation-harness, вы можете воспользоваться chat template и system instruction для моделей huggingface transformers формата