Spaces:
Running on Zero
Running on Zero
Download app.py from Kisho00/base-model: direct link, hf CLI and curl.
- Browser
- Download file 4.56 kB
-
https://huggingface.co/spaces/Kisho00/base-model/resolve/main/app.py
- Command line
-
hf download hf://spaces/Kisho00/base-model/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Kisho00/base-model/resolve/main/app.py
4.56 kB
| import json | |
| import os | |
| import time | |
| import gradio as gr | |
| import spaces | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| DEFAULT_MODEL_ID = "Kisho00/furi-phi4-mini-Final-V2" | |
| DEFAULT_REVISION = "b275abbef0c9a399625f73e1021068a7a7079d15" | |
| MODEL_ID = os.environ.get("FURI_MODEL_ID", DEFAULT_MODEL_ID) | |
| MODEL_REVISION = os.environ.get("FURI_MODEL_REVISION", DEFAULT_REVISION if MODEL_ID == DEFAULT_MODEL_ID else "main") | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, revision=MODEL_REVISION) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| MODEL_ID, revision=MODEL_REVISION, torch_dtype=torch.bfloat16, device_map="auto" | |
| ) | |
| model.eval() | |
| def read_messages(messages_json): | |
| messages = json.loads(messages_json) | |
| if not isinstance(messages, list) or not 1 <= len(messages) <= 32: | |
| raise ValueError("Invalid message list") | |
| for message in messages: | |
| if not isinstance(message, dict) or message.get("role") not in { | |
| "system", "user", "assistant" | |
| } or not isinstance(message.get("content"), str): | |
| raise ValueError("Invalid message") | |
| if sum(len(message["content"]) for message in messages) > 64000: | |
| raise ValueError("Context is too long") | |
| return messages | |
| def generate(messages, max_new_tokens, benchmark=False): | |
| token_limit = int(max_new_tokens) | |
| if not 16 <= token_limit <= 512: | |
| raise ValueError("Output budget must be between 16 and 512 tokens") | |
| inputs = tokenizer.apply_chat_template( | |
| messages, add_generation_prompt=True, return_tensors="pt", return_dict=True | |
| ).to(model.device) | |
| settings = dict(max_new_tokens=token_limit, do_sample=not benchmark, repetition_penalty=1.05) | |
| if not benchmark: | |
| settings.update(temperature=0.3, top_p=0.9) | |
| if torch.cuda.is_available(): | |
| torch.cuda.synchronize() | |
| started = time.perf_counter() | |
| with torch.inference_mode(): | |
| output = model.generate(**inputs, **settings) | |
| if torch.cuda.is_available(): | |
| torch.cuda.synchronize() | |
| inference_ms = (time.perf_counter() - started) * 1000 | |
| input_tokens = inputs["input_ids"].shape[-1] | |
| generated = output[0][input_tokens:] | |
| return { | |
| "reply": tokenizer.decode(generated, skip_special_tokens=True).strip(), | |
| "model": MODEL_ID, | |
| "modelRevision": MODEL_REVISION, | |
| "inferenceMillis": inference_ms, | |
| "inputTokens": input_tokens, | |
| "outputTokens": int(generated.shape[-1]), | |
| "maxNewTokens": token_limit, | |
| "sampling": not benchmark, | |
| "repetitionPenalty": 1.05, | |
| "precision": "bfloat16", | |
| "hardware": torch.cuda.get_device_name(0) if torch.cuda.is_available() else "CPU", | |
| } | |
| def chat(messages_json: str, max_new_tokens: int = 400): | |
| messages = read_messages(messages_json) | |
| domain_instruction = { | |
| "role": "system", | |
| "content": ( | |
| "Help with dog and cat care. Use the supplied pet context and the owner's latest question. " | |
| "Pet names and questions about cooking, walking, travel or behavior may be relevant pet-care questions. " | |
| "For a clearly unrelated topic or advice about another animal, briefly explain your dog-and-cat scope." | |
| ), | |
| } | |
| # Topic handling belongs to the model; a keyword such as 'cook' is not a refusal rule. | |
| return {"schema": "fursight.generation.v1", **generate([domain_instruction] + messages, max_new_tokens)} | |
| def evaluate(messages_json: str, max_new_tokens: int = 320): | |
| if MODEL_REVISION == "main": | |
| raise ValueError("Pin FURI_MODEL_REVISION to the model commit before research evaluation") | |
| # The benchmark preserves the supplied, identical prompts and returns raw model output. | |
| return generate(read_messages(messages_json), max_new_tokens, benchmark=True) | |
| with gr.Blocks() as demo: | |
| gr.Markdown("FurSight dog and cat care model") | |
| messages_input = gr.Textbox(label="messages_json") | |
| budget_input = gr.Slider(16, 512, value=400, step=1, label="max_new_tokens") | |
| with gr.Tab("Chat"): | |
| chat_output = gr.JSON(label="reply and generation metadata") | |
| gr.Button("Chat").click(chat, [messages_input, budget_input], chat_output, api_name="chat") | |
| with gr.Tab("Research evaluation"): | |
| evaluation_output = gr.JSON(label="Raw generation and timing") | |
| gr.Button("Evaluate").click( | |
| evaluate, [messages_input, budget_input], evaluation_output, api_name="evaluate" | |
| ) | |
| if __name__ == "__main__": | |
| demo.queue(default_concurrency_limit=1).launch() | |