Spaces:
Running
on
Zero
Running
on
Zero
| #!/usr/bin/env python | |
| from collections.abc import Iterator | |
| from threading import Thread | |
| import gradio as gr | |
| import spaces | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer | |
| MAX_INPUT_TOKEN_LENGTH = 4096 | |
| model_id = "Zyphra/Zamba2-7B-instruct" | |
| model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cuda", torch_dtype=torch.bfloat16) | |
| tokenizer = AutoTokenizer.from_pretrained(model_id) | |
| def generate( | |
| message: str, | |
| chat_history: list[dict], | |
| ) -> Iterator[str]: | |
| conversation = [*chat_history, {"role": "user", "content": message}] | |
| input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt") | |
| if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH: | |
| input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:] | |
| gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.") | |
| input_ids = input_ids.to(model.device) | |
| streamer = TextIteratorStreamer(tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True) | |
| generate_kwargs = dict( | |
| {"input_ids": input_ids}, | |
| streamer=streamer, | |
| max_new_tokens=MAX_INPUT_TOKEN_LENGTH, | |
| do_sample=False, | |
| num_beams=1, | |
| ) | |
| t = Thread(target=model.generate, kwargs=generate_kwargs) | |
| t.start() | |
| outputs = [] | |
| for text in streamer: | |
| outputs.append(text) | |
| yield "".join(outputs) | |
| demo = gr.ChatInterface( | |
| fn=generate, | |
| stop_btn=None, | |
| examples=[ | |
| ["Hello there! How are you doing?"], | |
| ["Can you explain briefly to me what is the Python programming language?"], | |
| ["Explain the plot of Cinderella in a sentence."], | |
| ["How many hours does it take a man to eat a Helicopter?"], | |
| ["Write a 100-word article on 'Benefits of Open-Source in AI research'"], | |
| ], | |
| cache_examples=False, | |
| type="messages", | |
| description="# Zamba2-7B-instruct", | |
| css_paths="style.css", | |
| ) | |
| if __name__ == "__main__": | |
| demo.queue(max_size=20).launch() | |