Spaces:
Running on Zero
Running on Zero
Download app.py from hugging-apps/jeeves-9b: direct link, hf CLI and curl.
- Browser
- Download file 12.8 kB
-
https://huggingface.co/spaces/hugging-apps/jeeves-9b/resolve/main/app.py
- Command line
-
hf download hf://spaces/hugging-apps/jeeves-9b/app.py
-
curl -L -o app.py https://huggingface.co/spaces/hugging-apps/jeeves-9b/resolve/main/app.py
12.8 kB
| import os | |
| import sys | |
| os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") | |
| import spaces # noqa: E402 (must precede torch) | |
| import torch # noqa: E402 | |
| import html # noqa: E402 | |
| import json # noqa: E402 | |
| import time # noqa: E402 | |
| import gradio as gr # noqa: E402 | |
| from huggingface_hub import snapshot_download # noqa: E402 | |
| from safetensors.torch import load_file # noqa: E402 | |
| # Vendored inference code from https://github.com/PostHog/jeeves (MIT). | |
| sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "jeeves_src")) | |
| import inference.engine as engine_mod # noqa: E402 | |
| from drafter.view import DrafterView # noqa: E402 | |
| from export import load_export # noqa: E402 | |
| from inference.api import parse_request, response # noqa: E402 | |
| from inference.types import Options # noqa: E402 | |
| MODEL_ID = "PostHog/jeeves" | |
| BLOCK = 4 # serving default drafter (block-4) | |
| MAX_ROWS = 8 # questions decoded in parallel | |
| MAX_LEN = 4096 # prompt + reasoning tokens per question | |
| WEIGHTS = snapshot_download( | |
| MODEL_ID, | |
| allow_patterns=["model-*.safetensors", "*.json", "head.pt", "tokenizer*", "vocab.json", "merges.txt", | |
| "chat_template.jinja", f"drafter_k{BLOCK}.safetensors"], | |
| ) | |
| # Build everything on CPU (bf16), then move to "cuda" eagerly so ZeroGPU can pack the weights. | |
| base, head, encoder = load_export(WEIGHTS, device="cpu") | |
| view = DrafterView(base, block=BLOCK) | |
| loaded = view.load_state_dict(load_file(os.path.join(WEIGHTS, f"drafter_k{BLOCK}.safetensors")), strict=False) | |
| _missing = [k for k in loaded.missing_keys if not k.startswith("base.")] | |
| if loaded.unexpected_keys or _missing: | |
| raise ValueError(f"drafter keys do not match: unexpected {loaded.unexpected_keys[:3]}, missing {_missing[:3]}") | |
| view.requires_grad_(False) | |
| for _proj in view.projections(): | |
| _proj.to(torch.bfloat16) | |
| view.to("cuda") | |
| head.to("cuda") | |
| print(f"Loaded {MODEL_ID}: temperature={head.temperature:.3f}, torch={torch.__version__}", flush=True) | |
| _ENGINE = None | |
| def get_engine(): | |
| """Build the Jeeves serving engine once per GPU worker (caches, CUDA graphs), reusing the preloaded weights.""" | |
| global _ENGINE | |
| if _ENGINE is None: | |
| engine_mod.load_export = lambda *a, **k: (base, head, encoder) | |
| engine_mod.DrafterView = lambda b, block: view | |
| engine_mod.load_file = lambda *a, **k: {n: t for n, t in view.state_dict().items() if not n.startswith("base.")} | |
| _ENGINE = engine_mod.Engine(WEIGHTS, "preloaded", block=BLOCK, precision="bf16", | |
| max_rows=MAX_ROWS, max_len=MAX_LEN, device="cuda") | |
| return _ENGINE | |
| def _parse_state(state: str): | |
| s = (state or "").strip() | |
| if s[:1] in "{[": | |
| try: | |
| return json.loads(s) | |
| except json.JSONDecodeError: | |
| pass | |
| return state | |
| def _bar(label: str, p: float, best: bool) -> str: | |
| pct = max(0.0, min(1.0, p)) * 100 | |
| color = "var(--color-accent)" if best else "var(--neutral-400)" | |
| weight = "700" if best else "400" | |
| return ( | |
| f"<div style='display:flex;align-items:center;gap:8px;margin:3px 0'>" | |
| f"<div style='flex:0 0 38%;font-weight:{weight};overflow:hidden;text-overflow:ellipsis;white-space:nowrap' " | |
| f"title='{html.escape(label)}'>{html.escape(label)}</div>" | |
| f"<div style='flex:1;background:var(--neutral-200);border-radius:4px;height:14px;overflow:hidden'>" | |
| f"<div style='width:{pct:.1f}%;background:{color};height:100%'></div></div>" | |
| f"<div style='flex:0 0 48px;text-align:right;font-variant-numeric:tabular-nums'>{p:.2f}</div></div>" | |
| ) | |
| def render(out: dict, questions: dict) -> str: | |
| parts = [] | |
| reasoning = out.get("reasoning", {}) | |
| for qid, a in out["answers"].items(): | |
| q = questions.get(qid, {}) | |
| instr = q.get("instructions") or "" | |
| if not isinstance(instr, str): | |
| instr = json.dumps(instr) | |
| body = [] | |
| if a["type"] == "noul": | |
| p = a["noul"] | |
| body.append(_bar("yes", p, p >= 0.5)) | |
| body.append(_bar("no", round(1 - p, 2), p < 0.5)) | |
| headline = f"<b>{'Yes' if p >= 0.5 else 'No'}</b> · P(yes) = {p:.2f}" | |
| elif a["type"] == "choice": | |
| for k, p in a["probabilities"].items(): | |
| body.append(_bar(k, p, k == a["choice"])) | |
| headline = f"<b>{html.escape(a['choice'])}</b> · confidence {a['confidence']:.2f}" | |
| else: | |
| mode = max(a["probabilities"], key=a["probabilities"].get) | |
| for k, p in a["probabilities"].items(): | |
| body.append(_bar(f"{k}: {a['legend'].get(k, '')}", p, k == mode)) | |
| headline = f"expected score <b>{a['score']:.2f}</b> · confidence {a['confidence']:.2f}" | |
| r = reasoning.get(qid) | |
| if r and r.get("thought"): | |
| note = "" if r.get("closed") else " (truncated at max_think)" | |
| body.append( | |
| f"<details style='margin-top:6px'><summary>Reasoning · {r['tokens']} tokens{note}</summary>" | |
| f"<div style='white-space:pre-wrap;font-size:0.9em;opacity:0.85;margin-top:4px'>{html.escape(r['text'])}</div></details>" | |
| ) | |
| elif r is not None: | |
| body.append("<div style='font-size:0.85em;opacity:0.7;margin-top:4px'>Answered without thinking.</div>") | |
| parts.append( | |
| f"<div style='border:1px solid var(--border-color-primary);border-radius:8px;padding:10px 12px;margin-bottom:10px'>" | |
| f"<div style='font-size:0.85em;opacity:0.7'><code>{html.escape(qid)}</code> · {a['type']}</div>" | |
| f"<div style='margin:2px 0 6px 0'>{html.escape(instr)}</div>" | |
| f"<div style='margin-bottom:6px'>{headline}</div>{''.join(body)}</div>" | |
| ) | |
| u = out["usage"] | |
| parts.append( | |
| f"<div style='font-size:0.85em;opacity:0.7'>{out['latency_ms'] / 1000:.1f}s · " | |
| f"{u['input_tokens']} input / {u['reasoning_tokens']} reasoning tokens</div>" | |
| ) | |
| return "<div>" + "".join(parts) + "</div>" | |
| def _duration(state, questions_json, think=True, max_think=1024, nothink_threshold=0.0, *args, **kwargs) -> int: | |
| # Measured on the Space: ~60 s one-off engine setup on a cold worker (Triton JIT + CUDA graphs), ~10 s fixed, | |
| # ~0.011 s per reasoning token per batch of up to 8 questions. +15% margin. | |
| try: | |
| n = max(1, len(json.loads(questions_json))) | |
| except Exception: | |
| n = 1 | |
| tokens = int(max_think) if think else 0 | |
| groups = -(-n // MAX_ROWS) | |
| return int(min(240, (70 + 0.011 * tokens * groups) * 1.15)) | |
| def decide(state: str, questions_json: str, think: bool = True, max_think: int = 1024, | |
| nothink_threshold: float = 0.0) -> tuple[str, dict]: | |
| """Answer yes/no, multiple-choice and rating questions about a state with Jeeves-9B. | |
| Args: | |
| state: The state to decide on: free text, or a JSON object/list. | |
| questions_json: JSON object of questions in Jev's /v1/systemone format, e.g. | |
| {"billing": {"type": "noul", "instructions": "Is this about billing?"}, | |
| "tone": {"type": "choice", "instructions": "Tone?", "criteria": {"calm": null, "angry": null}}, | |
| "urgency": {"type": "score", "instructions": "How urgent?", "criteria": ["low", "medium", "high"]}} | |
| think: Whether the model writes a reasoning chain before deciding. | |
| max_think: Maximum reasoning tokens per question (chains are truncated, then answered). | |
| nothink_threshold: If > 0, skip thinking for questions whose no-think confidence is at least this value. | |
| Returns: | |
| An HTML rendering of the answers and the raw Jev-format JSON response (with reasoning). | |
| """ | |
| try: | |
| questions = json.loads(questions_json) | |
| except json.JSONDecodeError as e: | |
| raise gr.Error(f"Questions must be valid JSON: {e}") | |
| body = { | |
| "state": _parse_state(state), | |
| "questions": questions, | |
| "options": { | |
| "think": bool(think), | |
| "max_think": int(max_think), | |
| "nothink_threshold": float(nothink_threshold) if nothink_threshold and nothink_threshold > 0 else None, | |
| "return_reasoning": True, | |
| }, | |
| } | |
| try: | |
| record, model, opts = parse_request(body, Options()) | |
| except (ValueError, KeyError) as e: | |
| raise gr.Error(str(e)) | |
| eng = get_engine() | |
| torch.cuda.synchronize() | |
| t0 = time.time() | |
| try: | |
| results = eng.answer(record, opts) | |
| except ValueError as e: | |
| raise gr.Error(str(e)) | |
| torch.cuda.synchronize() | |
| ms = (time.time() - t0) * 1000 | |
| out = response(record, model, opts, results, eng.encoder.tok, ms) | |
| return render(out, questions), out | |
| def _q(d: dict) -> str: | |
| return json.dumps(d, indent=2) | |
| EXAMPLES = [ | |
| [ | |
| "Shoes arrived two weeks late and in the wrong size. Also I see two charges on my card.", | |
| _q({ | |
| "department": {"type": "choice", "instructions": "Which team should handle this?", | |
| "criteria": {"returns": "Exchanges, refunds, wrong or damaged items", | |
| "shipping": "Delivery status, delays, lost packages", | |
| "billing": "Charges, invoices, payment problems"}}, | |
| "escalate": {"type": "noul", "instructions": "Does this need urgent human attention?"}, | |
| "frustration": {"type": "score", "instructions": "How frustrated is the customer?", | |
| "criteria": ["Calm", "Frustrated", "Very angry"]}, | |
| }), | |
| ], | |
| [ | |
| "I was charged twice for one order.", | |
| _q({ | |
| "billing": {"type": "noul", "instructions": "Is this about billing?"}, | |
| "tone": {"type": "choice", "instructions": "What is the customer's tone?", | |
| "criteria": {"calm": None, "frustrated": None, "angry": None}}, | |
| }), | |
| ], | |
| [ | |
| "I was charged twice. Please help.", | |
| _q({ | |
| "billing": {"type": "noul", "instructions": "Is this about billing?"}, | |
| "tone": {"type": "choice", "instructions": "What is the tone?", "criteria": {"calm": None, "angry": None}}, | |
| "urgency": {"type": "score", "instructions": "How urgent is this?", | |
| "criteria": ["can wait", "this week", "today"]}, | |
| }), | |
| ], | |
| ] | |
| CSS = """ | |
| #col-container { max-width: 1200px; margin: 0 auto; } | |
| .dark .gradio-container { color: var(--body-text-color); } | |
| """ | |
| with gr.Blocks(title="Jeeves-9B") as demo: | |
| with gr.Column(elem_id="col-container"): | |
| gr.Markdown( | |
| "# Jeeves-9B\n" | |
| "A Jev-like decision model that **reasons before it decides**. Give it a state (text or JSON) and " | |
| "yes/no (`noul`), multiple-choice (`choice`) or rating (`score`) questions; it writes a reasoning chain " | |
| "per question and returns a calibrated probability for every option.\n\n" | |
| "[Model](https://huggingface.co/PostHog/jeeves) · [Code](https://github.com/PostHog/jeeves)" | |
| ) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| state = gr.Textbox(label="State (text or JSON)", lines=4, value=EXAMPLES[0][0], | |
| placeholder="e.g. a customer message, a ticket, a JSON record…") | |
| questions = gr.Code(label="Questions (Jev /v1/systemone format)", language="json", | |
| value=EXAMPLES[0][1], lines=14) | |
| run = gr.Button("Decide", variant="primary") | |
| with gr.Accordion("Advanced options", open=False): | |
| think = gr.Checkbox(label="Think before deciding", value=True) | |
| max_think = gr.Slider(label="max_think (reasoning tokens per question)", minimum=0, | |
| maximum=2560, step=64, value=1024) | |
| nothink_threshold = gr.Slider( | |
| label="nothink_threshold (0 = off; skip thinking when the no-think answer is this confident)", | |
| minimum=0.0, maximum=1.0, step=0.05, value=0.0) | |
| with gr.Column(scale=1): | |
| answers = gr.HTML(label="Answers") | |
| with gr.Accordion("Raw JSON response", open=False): | |
| raw = gr.JSON(label="Response") | |
| gr.Examples( | |
| examples=EXAMPLES, | |
| inputs=[state, questions], | |
| outputs=[answers, raw], | |
| fn=decide, | |
| cache_examples=True, | |
| cache_mode="lazy", | |
| ) | |
| run.click(decide, inputs=[state, questions, think, max_think, nothink_threshold], outputs=[answers, raw], | |
| api_name="decide") | |
| if __name__ == "__main__": | |
| demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True) | |