Spaces:
Paused
Paused
| import gradio as gr | |
| from transformers import AutoTokenizer, AutoModelForCausalLM | |
| from spaces import GPU as gpu | |
| class Delta: | |
| def __init__(self, content): | |
| self.content = content | |
| class Choice: | |
| def __init__(self, delta): | |
| self.delta = delta | |
| class InferenceClient: | |
| def __init__(self, model_id="nroggendorff/smallama-it"): | |
| self.tokenizer = AutoTokenizer.from_pretrained(model_id) | |
| self.model = AutoModelForCausalLM.from_pretrained(model_id) | |
| class ModelOutput: | |
| def __init__(self, client, inputs): | |
| self.client = client | |
| self.inputs = inputs | |
| self.choices = [] | |
| def decode(self, output): | |
| decoded_output = self.client.tokenizer.decode( | |
| output[0][self.inputs["input_ids"].shape[-1] :], | |
| skip_special_tokens=True, | |
| ) | |
| self.choices = [Choice(Delta(decoded_output))] | |
| return self | |
| def chat_completion( | |
| self, messages, max_tokens=256, stream=True, temperature=0.2, top_p=0.95 | |
| ): | |
| inputs = self.tokenizer.apply_chat_template( | |
| messages, | |
| add_generation_prompt=True, | |
| tokenize=True, | |
| return_dict=True, | |
| return_tensors="pt", | |
| ).to(self.model.device) | |
| model_output = self.ModelOutput(self, inputs) | |
| for _ in range(max_tokens): | |
| output = self.model.generate( | |
| **inputs, max_new_tokens=1, temperature=temperature, top_p=top_p | |
| ) | |
| yield model_output.decode(output) | |
| def respond( | |
| message, | |
| history: list[dict[str, str]], | |
| system_message, | |
| max_tokens, | |
| temperature, | |
| top_p, | |
| ): | |
| client = InferenceClient() | |
| messages = [{"role": "system", "content": system_message}] | |
| messages.extend(history) | |
| messages.append({"role": "user", "content": message}) | |
| response = "" | |
| for message in client.chat_completion( | |
| messages, | |
| max_tokens=max_tokens, | |
| stream=True, | |
| temperature=temperature, | |
| top_p=top_p, | |
| ): | |
| choices = message.choices | |
| token = "" | |
| if len(choices) and choices[0].delta.content: | |
| token = choices[0].delta.content | |
| response += token | |
| yield response | |
| chatbot = gr.ChatInterface( | |
| respond, | |
| type="messages", | |
| additional_inputs=[ | |
| gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"), | |
| gr.Slider(minimum=0.1, maximum=4.0, value=0.2, step=0.1, label="Temperature"), | |
| gr.Slider( | |
| minimum=0.1, | |
| maximum=1.0, | |
| value=0.95, | |
| step=0.05, | |
| label="Top-p (nucleus sampling)", | |
| ), | |
| ], | |
| ) | |
| with gr.Blocks() as demo: | |
| chatbot.render() | |
| if __name__ == "__main__": | |
| demo.launch() | |