File size: 2,905 Bytes
ce03581
be678b6
 
ce03581
be678b6
 
 
 
ce03581
be678b6
 
 
 
 
 
 
ce03581
 
 
 
 
 
 
 
 
be678b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce03581
be678b6
ce03581
 
 
be678b6
 
 
ce03581
 
 
be678b6
ce03581
 
 
 
be678b6
 
ce03581
 
 
be678b6
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
85
86
87
88
89
90
import gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

# Load your fine-tuned model
model_id = "ragunath-ravi/distilgpt2-lmsys-chat"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id)

# Set padding token to be the same as EOS token if not set
if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token

# Move model to GPU if available
device = "cuda" if torch.cuda.is_available() else "cpu"
model = model.to(device)

def respond(
    message,
    history: list[tuple[str, str]],
    system_message,
    max_tokens,
    temperature,
    top_p,
):
    # Format the conversation history as expected by the model
    prompt = system_message + "\n\n"
    
    for user_msg, assistant_msg in history:
        if user_msg:
            prompt += f"User: {user_msg}\n"
        if assistant_msg:
            prompt += f"Assistant: {assistant_msg}\n"
    
    # Add the latest user message
    prompt += f"User: {message}\nAssistant:"
    
    # Tokenize the prompt
    inputs = tokenizer(prompt, return_tensors="pt").to(device)
    
    # Generate response
    with torch.no_grad():
        output = model.generate(
            inputs["input_ids"],
            max_new_tokens=max_tokens,
            temperature=temperature,
            top_p=top_p,
            do_sample=True,
            pad_token_id=tokenizer.eos_token_id,
            attention_mask=inputs["attention_mask"],
        )
    
    # Decode the generated response
    full_response = tokenizer.decode(output[0], skip_special_tokens=True)
    
    # Extract only the assistant's part from the full response
    assistant_response = full_response[len(prompt):].strip()
    
    # Sometimes the model might continue with "User:" - we need to cut that off
    if "User:" in assistant_response:
        assistant_response = assistant_response.split("User:")[0].strip()
    
    # Stream the response token by token (simulated for this model)
    response_so_far = ""
    tokens = assistant_response.split()
    for token in tokens:
        response_so_far += token + " "
        yield response_so_far.strip()

# Create the Gradio chat interface
demo = gr.ChatInterface(
    respond,
    additional_inputs=[
        gr.Textbox(value="You are a helpful assistant.", label="System message"),
        gr.Slider(minimum=1, maximum=512, value=128, step=1, label="Max new tokens"),
        gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature"),
        gr.Slider(
            minimum=0.1,
            maximum=1.0,
            value=0.9,
            step=0.05,
            label="Top-p (nucleus sampling)",
        ),
    ],
    title="DistilGPT-2 Chat Assistant",
    description="A simple chatbot powered by a fine-tuned DistilGPT-2 model on the LMSYS Chat 1M dataset.",
)

if __name__ == "__main__":
    demo.launch()