File size: 1,397 Bytes
c35409b
 
 
 
 
 
d9bbbfc
 
c35409b
 
 
 
 
 
 
 
 
 
 
 
 
 
e40a429
 
 
c35409b
 
e40a429
 
 
 
c35409b
e40a429
c35409b
e40a429
c35409b
 
602b318
 
c35409b
 
 
 
3cf0ef6
af2a5f9
c35409b
 
37c1e63
e40a429
 
 
c35409b
 
 
 
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
import spaces
import gradio as gr
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer


device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

def load_model():
    model_id = "nanochat-students/chat-d20"

    tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=False)
    model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=False, dtype=torch.bfloat16).to(device)
    model.eval()

    return tokenizer, model

tokenizer, model = load_model()


@spaces.GPU
def generate(prompt, history):
    
    if len(history) > 0:
        messages = history + [
        {"role": "user", "content": prompt},
    ]
    else:
        messages = [
            {"role": "user", "content": prompt},
        ]

    print(history)
    inputs = tokenizer.apply_chat_template(
        messages,
        add_generation_prompt=True,
        tokenize=True,
        return_tensors="pt",
        return_dict=True,
    ).to(device)
    
    with torch.no_grad():
        outputs = model.generate(
            **inputs,
            max_new_tokens=512,
        )
    
    generated_tokens = outputs[0, inputs.input_ids.shape[1]:]
    output = tokenizer.decode(generated_tokens, skip_special_tokens=True)

    return output


demo = gr.ChatInterface(fn=generate, type="messages", examples=["hello", "hola", "merhaba"], title="NanoChat")
demo.launch()