"""Ivonnet-0.8B — typed decisions with calibrated probabilities, no decoding. Illuin's Ivonnet-0.8B does not generate text. You hand the model a *state* — plain text, JSON, an image, or any combination — plus a set of typed questions — `choice` (pick one of up to 255 named options), `noul` (yes/no), or `score` (an ordered scale) — and it returns a calibrated probability for every option, read in a single forward pass: the hidden state at the generation position goes through a linear readout over 255 single-token answer codes, softmaxed at the checkpoint's fitted temperature. This Space wraps [`illuin/Ivonnet-0.8B`](https://huggingface.co/illuin/Ivonnet-0.8B) (0.85 B params on a Qwen3.5-0.8B hybrid-attention backbone — 18 Gated DeltaNet linear-attention layers + 6 non-causal full-attention layers — bf16, ~1.7 GB) with the authors' own `decision_model` package loaded straight from the checkpoint's `source/` directory, at the fitted temperature 1.447 saved in `decision_config.json`. """ import json import os import sys import time from pathlib import Path os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") import spaces # noqa: E402 (must precede any CUDA-touching import) import gradio as gr MODEL_ID = "illuin/Ivonnet-0.8B" # --------------------------------------------------------------------------------------------- # Model — the authors' own loading recipe, verbatim except for one deferral. The weights # are fetched from the Hub by the Space itself; the checkpoint ships its inference package # in `source/src`, which goes on sys.path. # # DecisionModel.__init__ ends with `self.attention_check = self.check_attention()` — REAL # forward passes that verify the non-causal full attention on the mask that actually # reaches a full-attention layer. ZeroGPU's main process has no GPU, so the check cannot # run at module scope: it is deferred to the first @spaces.GPU call (see _ensure_ready), # where it runs unchanged, together with the authors' warmup(). The attention SETUP itself # (the mask mapping on transformers >= 5.13, `is_causal = False` on the full-attention # layers) happens in __init__ and needs no GPU. # --------------------------------------------------------------------------------------------- from huggingface_hub import snapshot_download # noqa: E402 CHECKPOINT = Path(snapshot_download(MODEL_ID)) sys.path.insert(0, str(CHECKPOINT / "source" / "src")) from decision_model import DecisionModel, InputTooLong, UnsupportedQuestion # noqa: E402 _REAL_CHECK_ATTENTION = DecisionModel.check_attention DecisionModel.check_attention = lambda self: {"deferred": "runs on the first GPU call"} try: MODEL = DecisionModel.from_pretrained(CHECKPOINT, device="cuda") finally: DecisionModel.check_attention = _REAL_CHECK_ATTENTION CALIBRATED_TEMPERATURE = MODEL.temperature # fitted on held-out data; must not be overridden _READY = {"ok": False} # per-worker flag: flips on the first @spaces.GPU call _READY_FLAG = Path("/tmp/ivonnet_warm.flag") # and this one crosses the fork boundary def _ensure_ready() -> None: """Once per worker: run the model's own attention check and its warmup, on the GPU. `check_attention` refuses to serve if the full-attention layers see anything but the padding-only mask — the same guarantee the package enforces at load time everywhere else. `warmup` compiles and tunes the Gated DeltaNet Triton kernels for the request shapes, exactly as the authors' server does at startup. """ if _READY["ok"]: return MODEL.attention_check = MODEL.check_attention() MODEL.warmup() _READY["ok"] = True try: # tells the main process (and later cold workers) the kernels are compiled _READY_FLAG.write_text("ok") except OSError: pass def _gpu_duration(*_args, **_kwargs) -> int: """Duration follows the call, not the worst case. The `spaces` runtime evaluates this callable in the MAIN process before the worker forks, so the per-worker `_READY` dict is always False there — readiness is signalled through the filesystem instead, the same way the Triton compile cache is shared across workers. A cold first call (fresh container, empty Triton cache) pays weight streaming + the attention check + Triton warmup-with-compile — measured at 37 s end to end; every later call only pays the forward pass (measured 0.3–0.5 s wall, 40–100 ms GPU). A worker that is new but finds the warm on-disk cache only re-runs check + warmup (a few seconds), which the warm duration also covers.""" return 30 if _READY_FLAG.exists() else 60 # --------------------------------------------------------------------------------------------- # Question-block DSL: one paragraph per question, glued into a single textbox so the UI # stays one input for the questions dict, in author order. Every block: # # [choice] ← question line: [type] then instructions # option-name: description ← one line per option (description optional) # option-name # ... # # [score] # level 1 description # level 2 description # ... # # [noul] # (optionally `yes: ...` / `no: ...` description lines) # # Question IDs are derived from the instructions' first words (the model never sees IDs, # only the rendered question), and are made unique if two questions share a prefix. # --------------------------------------------------------------------------------------------- def parse_questions(block_text: str) -> dict: """Convert the question textbox into the decision_model `questions` dict (in order).""" questions: dict = {} for para in block_text.replace("\r\n", "\n").strip().split("\n\n"): lines = [ln.strip() for ln in para.split("\n") if ln.strip()] if not lines: continue head = lines[0] kind = next((k for k in ("choice", "noul", "score") if head.startswith(f"[{k}]")), None) if kind is None: raise ValueError( f"Every question block must start with [choice], [noul] or [score] — got: {head!r}" ) instructions = head[len(f"[{kind}]"):].strip() or None body = lines[1:] if kind == "choice": criteria: dict = {} for ln in body: if ":" in ln: name, desc = ln.split(":", 1) else: name, desc = ln, None name = name.strip() if not name: raise ValueError(f"A choice option line has no option name: {ln!r}") criteria[name] = desc.strip() if desc else None if not criteria: raise ValueError(f"A [choice] question needs at least one option line: {head!r}") question = {"type": "choice", "criteria": criteria, "instructions": instructions} elif kind == "score": levels = [ln for ln in body] if len(levels) < 2: raise ValueError(f"A [score] question needs at least two level lines: {head!r}") question = {"type": "score", "criteria": levels, "instructions": instructions} else: # noul criteria = {"true": None, "false": None} for ln in body: if ln[:3].lower() == "yes": criteria["true"] = ln[3:].lstrip(":- ").strip() or None elif ln[:2].lower() == "no": criteria["false"] = ln[2:].lstrip(":- ").strip() or None else: raise ValueError( f"A [noul] block may only carry 'yes: ...' / 'no: ...' description " f"lines: {ln!r}" ) question = {"type": "noul", "criteria": criteria, "instructions": instructions} # Stable, unique-ish IDs from the instructions (or the type, if no instructions). base = " ".join((instructions or kind).split()[:3]).lower() qid = "".join(ch if ch.isalnum() else "_" for ch in base).strip("_") or kind while qid in questions: qid = f"{qid}_" questions[qid] = question if not questions: raise ValueError("Define at least one question block.") return questions def _fmt_pct(p: float) -> str: return f"{p * 100:.1f}%" def _bar(p: float, width: int = 26) -> str: filled = int(round(p * width)) return "█" * filled + "░" * max(0, width - filled) def render_answers(answers: dict, questions: dict) -> str: """Render the decisions as Markdown verdict cards, one section per question.""" out: list[str] = [] for qid, ans in answers.items(): q = questions[qid] kind = ans["type"] instructions = q.get("instructions") or "Choose the best matching option." out.append(f"### {instructions}") if kind == "noul": p_true = ans["noul"] verdict = "**YES**" if p_true >= 0.5 else "**NO**" out.append(f"{verdict} — P(true) = **{p_true:.3f}**\n") out.append(f"`{_bar(p_true)}` yes {_fmt_pct(p_true)} · no {_fmt_pct(1 - p_true)}\n") elif kind == "choice": probs = ans["probabilities"] best = ans["choice"] out.append(f"**{best}**\n") ordered = sorted(probs.items(), key=lambda kv: kv[1], reverse=True) for name, p in ordered: mark = " ←" if name == best else "" out.append(f"- `{_bar(p)}` {_fmt_pct(p)} {name}{mark}") out.append("") else: # score: levels are the question's criteria list, keyed "0", "1", ... levels = list(q["criteria"]) probs = ans["probabilities"] score = ans["score"] best_ix = max(probs, key=probs.get) out.append( f"expected level **{score:.2f}** — most likely `{levels[int(best_ix)]}`\n" ) ranked = sorted(probs.items(), key=lambda kv: kv[1], reverse=True) for ix, p in ranked: out.append(f"- `{_bar(p)}` {_fmt_pct(p)} level {ix}: {levels[int(ix)]}") out.append("") return "\n".join(out) # --------------------------------------------------------------------------------------------- # Inference # --------------------------------------------------------------------------------------------- @spaces.GPU(duration=_gpu_duration) def decide(state: str, questions_text: str, image=None, style: str = "text") -> tuple[str, str]: """Answer typed decision questions about a state (and optional image) in one forward pass. Args: state: The context to classify — plain text or JSON. Questions are answered from it. questions_text: Question blocks, one paragraph per question. A block starts with `[choice]`/`[noul]`/`[score]` plus optional instructions, then one line per option (choice: `name: description`), per level (score), or optional `yes:`/`no:` descriptions (noul). image: Optional image. Placed before the state; every question sees it. style: Prompt protocol — "text" (options as `key: description`, the model card's usage path) or "vision" (the Decision Index vision board protocol: option descriptions alone, no default instructions). Returns: Markdown verdict cards plus the raw decisions-API JSON. """ if not (state and state.strip()): raise gr.Error("Give the decision a state — the text (or JSON) context to classify.") # `state` accepts text or any JSON value; hand the model the parsed object when it is one. try: parsed = json.loads(state) except (json.JSONDecodeError, ValueError): parsed = state if not isinstance(parsed, (dict, list)): parsed = state try: questions = parse_questions(questions_text or "") except ValueError as exc: raise gr.Error(str(exc)) from None try: _ensure_ready() except RuntimeError as exc: # the model's own attention check refused to serve raise gr.Error(f"attention check failed: {exc}") from None images = [image] if image is not None else () t0 = time.perf_counter() try: result = MODEL.decide(parsed, questions, images=images, style=style) except (InputTooLong, UnsupportedQuestion) as exc: raise gr.Error(str(exc)) from None elapsed = time.perf_counter() - t0 answers = result["answers"] header = ( f"### {len(answers)} question{'s' if len(answers) != 1 else ''} · {style} protocol · " f"**{elapsed * 1000:.0f} ms** · {result['usage']['input_tokens']:,} input tokens" ) cards = render_answers(answers, questions) raw = json.dumps(result, indent=2, ensure_ascii=False) return f"{header}\n\n{cards}", raw # --------------------------------------------------------------------------------------------- # Default inputs — the canonical example is the model card's own usage sample # --------------------------------------------------------------------------------------------- CANONICAL_STATE = "My integration keeps failing with a 401." CANONICAL_QUESTIONS = """[choice] Which team should handle this request? billing: Charges and refunds support: Technical integration errors sales: Questions about buying a product [noul] Is the customer blocked?""" TICKET_STATE = """{"ticket_id": "T-4187", "channel": "email", "priority": "P2", "message": "I was charged twice for my March invoice and the refund still hasn't landed.", "plan": "Pro monthly", "previous_tickets": 3, "last_refund_request_days_ago": 12}""" TICKET_QUESTIONS = """[choice] Which team should handle this ticket? billing: Charges, invoices and refunds support: Technical defects and bug reports sales: Plan upgrades and new purchases [noul] Does the customer mention any technical error or broken feature? [score] How urgent does the customer's tone sound? routine elevated urgent""" CAT_STATE = ( "The customer sent this photo with their message: 'Is this thing safe to pet? It has been " "staring at me from under the couch for an hour.'" ) CAT_QUESTIONS = """[choice] What animal is in the photo? cat dog rabbit ferret [noul] Are the animal's eyes open? [score] How calm does the animal look? agitated alert relaxed asleep""" SIGN_STATE = ( "A beach-scene photo crawled by our content pipeline. Read it as the customers see it and " "classify the shot for the storefront." ) SIGN_QUESTIONS = """[choice] What does the letter-board sign in the image say? SUMMER TIME BEACH DAY SUNSET HOUR GOOD VIBES [noul] Does the image contain a film camera? [score] How prominent is the ocean in the frame? not visible distant haze clear midground dominant""" CSS = """ #col-container { max-width: 1150px; margin: 0 auto; } .dark .gradio-container { color: var(--body-text-color); } """ with gr.Blocks(title="ivonnet", fill_width=True) as demo: with gr.Column(elem_id="col-container"): gr.Markdown( "# Ivonnet-0.8B\n" "Illuin's small **typed decision** model: give it a state and typed questions — " "**choice** (pick one of up to 255 options), **noul** (yes / no), **score** (an " "ordered scale) — and it returns a **calibrated probability** for every option in " "**one forward pass, zero generated tokens**, read through a 255-answer-code " "linear readout at the fitted temperature 1.447.\n\n" "0.85 B params on a Qwen3.5-0.8B hybrid-attention backbone (18 Gated DeltaNet " "linear-attention layers + 6 non-causal full-attention layers), bf16 (~1.7 GB), " "38 ms per text question. [model card](https://huggingface.co/illuin/Ivonnet-0.8B)" ) with gr.Row(): with gr.Column(scale=3): state_input = gr.Textbox( value=CANONICAL_STATE, label="State", lines=4, placeholder="The context to classify — plain text or JSON.", info="Non-string states are serialized as JSON. Put everything the questions " "need in here — questions never see each other, only the state.", ) img_input = gr.Image( type="pil", label="Image (optional)", height=280, ) with gr.Column(scale=4): questions_input = gr.Code( value=CANONICAL_QUESTIONS, language=None, label="Questions", lines=18, buttons=[], ) gr.Markdown( "**Questions** — one paragraph per question. First line: `[choice]` / `[noul]` / " "`[score]` + optional instructions. Then: choice → one `option: description` per " "line (description optional); score → one level per line (lowest first); noul → " "optional `yes:`/`no:` descriptions. **Image** is placed before the state; every " "question sees it (aspect ratio kept, sides multiples of 32 px). A question row " "longer than 32,768 tokens or with more than 255 options is refused, never " "truncated." ) run = gr.Button("Decide", variant="primary") verdict = gr.Markdown("Verdict cards appear here.") with gr.Accordion("Raw decisions (API JSON)", open=False): raw_json = gr.Code(language="json", label="Response", buttons=["copy"], lines=14) with gr.Accordion("Advanced", open=False): style_input = gr.Radio( choices=["text", "vision"], value="text", label="Prompt protocol", info="'text' renders options as `key: description` (the model card's usage " "path); 'vision' is the Decision Index vision-board protocol — option " "descriptions alone and no default instructions. This is prompt " "rendering only; it is independent of whether an image is attached.", ) gr.Examples( examples=[ [CANONICAL_STATE, CANONICAL_QUESTIONS], [TICKET_STATE, TICKET_QUESTIONS], ], inputs=[state_input, questions_input], outputs=[verdict, raw_json], fn=decide, cache_examples=True, cache_mode="lazy", label="Text examples — the model card's own usage sample, then a JSON ticket", ) gr.Examples( examples=[ [CAT_STATE, CAT_QUESTIONS, "examples/cat_tabby.jpg"], [SIGN_STATE, SIGN_QUESTIONS, "examples/sign_beach.jpg"], ], inputs=[state_input, questions_input, img_input], outputs=[verdict, raw_json], fn=decide, cache_examples=True, cache_mode="lazy", label="Vision examples — photos rated by the typed questions", ) run.click( fn=decide, inputs=[state_input, questions_input, img_input, style_input], outputs=[verdict, raw_json], api_name="decide", ) if __name__ == "__main__": demo.queue(max_size=32) demo.launch(mcp_server=True, ssr_mode=False, theme=gr.themes.Citrus(), css=CSS)