import gradio as gr import spaces import torch from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer from threading import Thread MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct" tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) model = AutoModelForCausalLM.from_pretrained( MODEL_ID, torch_dtype=torch.bfloat16, device_map="auto" ) @spaces.GPU def chat_function(message, history): messages = [] for user_msg, assistant_msg in history: messages.append({"role": "user", "content": user_msg}) messages.append({"role": "assistant", "content": assistant_msg}) messages.append({"role": "user", "content": message}) # 1. Render the chat template as a string prompt = tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True ) # 2. Tokenize the string and move to the GPU inputs = tokenizer(prompt, return_tensors="pt").to(model.device) streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True) # 3. Explicitly pass input_ids and attention_mask generation_kwargs = dict( input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"], streamer=streamer, max_new_tokens=512, do_sample=True, temperature=0.7, top_p=0.9 ) thread = Thread(target=model.generate, kwargs=generation_kwargs) thread.start() partial_text = "" for new_text in streamer: partial_text += new_text yield partial_text demo = gr.ChatInterface( fn=chat_function, title="Qwen2.5-1.5B Chatbot", description="A lightweight LLM running on Hugging Face Spaces using ZeroGPU.", ) if __name__ == "__main__": demo.launch()