File size: 2,514 Bytes
de2c662
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig
from peft import PeftModel, PeftConfig

MODEL_NAME = "IlyaGusev/llama_7b_ru_turbo_alpaca_lora"

tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
config = PeftConfig.from_pretrained(MODEL_NAME)
model = AutoModelForCausalLM.from_pretrained(
    config.base_model_name_or_path,
    load_in_8bit=True,
    device_map="auto"
)
model = PeftModel.from_pretrained(model, MODEL_NAME)
model.eval()


def generate_prompt(instruction, input=None):
    if input:
        return f"Задание: {instruction}\nВход: {input}\nОтвет:"
    return f"Задание: {instruction}\n\nОтвет:"


def evaluate(
    instruction,
    input=None,
    temperature=1.0,
    top_p=1.0,
    top_k=40,
    num_beams=3,
    max_new_tokens=256,
    **kwargs,
):
    prompt = generate_prompt(instruction, input)
    inputs = tokenizer(prompt, return_tensors="pt")
    input_ids = inputs["input_ids"].to(model.device)
    generation_config = GenerationConfig(
        temperature=temperature,
        top_p=top_p,
        top_k=top_k,
        num_beams=num_beams,
        **kwargs,
    )
    with torch.no_grad():
        generation_output = model.generate(
            input_ids=input_ids,
            generation_config=generation_config,
            return_dict_in_generate=True,
            output_scores=True,
            max_new_tokens=max_new_tokens
        )
    s = generation_output.sequences[0]
    output = tokenizer.decode(s, skip_special_tokens=True)
    return output.strip()


g = gr.Interface(
    fn=evaluate,
    inputs=[
        gr.components.Textbox(
            lines=2, label="Задание", placeholder="Почему трава зеленая?"
        ),
        gr.components.Textbox(lines=2, label="Вход", placeholder="Нет"),
        gr.components.Slider(minimum=0, maximum=2, value=1.0, label="Temperature"),
        gr.components.Slider(minimum=0, maximum=1, value=0.8, label="Top p"),
        gr.components.Slider(minimum=0, maximum=100, value=40, label="Top k"),
        gr.components.Slider(minimum=1, maximum=5, step=1, value=4, label="Beams"),
        gr.components.Slider(
            minimum=1, maximum=256, step=1, value=256, label="Max tokens"
        ),
    ],
    outputs=[
        gr.inputs.Textbox(
            lines=5,
            label="Output",
        )
    ],
    title="LLaMA 7B Ru Turbo Alpaca",
    description="",
)
g.queue(concurrency_count=1)
g.launch()