File size: 1,458 Bytes
c35409b
 
 
 
 
 
d9bbbfc
 
c35409b
 
49793a8
 
 
 
 
 
c35409b
 
 
 
 
 
 
 
9a8c7e2
8f42a5a
 
 
9a8c7e2
 
8f42a5a
 
 
 
fa7335c
8f42a5a
c35409b
8f42a5a
c35409b
 
d702853
8f42a5a
c35409b
 
 
 
3cf0ef6
fabb44a
c35409b
 
37c1e63
8f42a5a
 
 
c35409b
 
 
9a8c7e2
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
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="karpathy/nanochat-d32"
    revision="refs/pr/1"
    
    tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=False, revision=revision)
    model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=False, dtype=torch.bfloat16, revision=revision).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()