Spaces:
Sleeping

File size: 1,896 Bytes
1d1116b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import spaces
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

MODEL_ID = "Notbobjoe/TalkT2-0.1b"

# Load the model on CPU; ZeroGPU grants GPU only while a decorated function runs.
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
model = AutoModelForCausalLM.from_pretrained(MODEL_ID)
model.eval()

@spaces.GPU(duration=60)
def generate_reply(message, history):
    message = (message or "").strip()
    if not message:
        return ""

    # Preserve TalkT2's familiar prompt format.
    prompt = "You: " + message + "\nTalkT2:"
    inputs = tokenizer(prompt, return_tensors="pt")

    try:
        model.to("cuda")
        inputs = {k: v.to("cuda") for k, v in inputs.items()}
        with torch.inference_mode():
            output = model.generate(
                **inputs,
                max_new_tokens=100,
                do_sample=True,
                temperature=0.4,
                top_p=0.95,
                top_k=50,
                repetition_penalty=1.1,
                pad_token_id=tokenizer.eos_token_id,
                eos_token_id=tokenizer.eos_token_id,
            )
        new_tokens = output[0, inputs["input_ids"].shape[1]:]
        reply = tokenizer.decode(new_tokens, skip_special_tokens=True)
        # Stop if the model begins another speaker turn.
        reply = reply.split("\nYou:", 1)[0].split("\nTalkT2:", 1)[0].strip()
        return reply or "(TalkT2 returned an empty response.)"
    finally:
        model.to("cpu")
        if torch.cuda.is_available():
            torch.cuda.empty_cache()

demo = gr.ChatInterface(
    fn=generate_reply,
    title="TalkT2-0.1b",
    description="Experimental TalkT2 chatbot hosted on Hugging Face Spaces.",
    examples=["Hello, who are you?", "What do you think about creativity?"],
)

# Gradio creates its public app and API automatically.
demo.queue().launch()