Spaces:
Running on Zero
Running on Zero
Upload folder using huggingface_hub
Browse files- .gitattributes +2 -0
- README.md +90 -7
- app.py +432 -0
- examples/cat_tabby.jpg +3 -0
- examples/sign_beach.jpg +3 -0
- requirements.txt +10 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
examples/cat_tabby.jpg filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
examples/sign_beach.jpg filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
|
@@ -1,13 +1,96 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.32.0
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
-
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: ivonnet
|
| 3 |
+
emoji: π―
|
| 4 |
+
colorFrom: red
|
| 5 |
+
colorTo: yellow
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.32.0
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
+
short_description: Typed decisions with calibrated probabilities, no decoding
|
| 10 |
+
python_version: "3.12"
|
| 11 |
+
startup_duration_timeout: 1h
|
| 12 |
---
|
| 13 |
|
| 14 |
+
# Ivonnet-0.8B β typed decisions in one forward pass
|
| 15 |
+
|
| 16 |
+
A Gradio demo for [`illuin/Ivonnet-0.8B`](https://huggingface.co/illuin/Ivonnet-0.8B)
|
| 17 |
+
(Apache-2.0), Illuin's small **typed decision model**, distilled from
|
| 18 |
+
[IVE-4B](https://huggingface.co/illuin/IVE-4B) and fine-tuned from
|
| 19 |
+
[Qwen/Qwen3.5-0.8B](https://huggingface.co/Qwen/Qwen3.5-0.8B).
|
| 20 |
+
|
| 21 |
+
The model does **not generate text**. You hand it a *state* β plain text, JSON, an image,
|
| 22 |
+
or any combination β plus a set of **typed questions**, and it returns a **calibrated
|
| 23 |
+
probability distribution** for every option in a single forward pass: the hidden state at
|
| 24 |
+
the generation position goes through a linear readout over 255 single-token answer codes
|
| 25 |
+
(A to Z, then AA, AB, β¦), softmaxed at the checkpoint's fitted temperature, 1.447.
|
| 26 |
+
|
| 27 |
+
- **`choice`** β pick one of up to 255 named options.
|
| 28 |
+
- **`noul`** β a yes/no question with no unsatisfactory-option list ("none of the above").
|
| 29 |
+
- **`score`** β an ordered scale of 2β255 levels; the answer is the expected level *and* the
|
| 30 |
+
full probability mass over levels.
|
| 31 |
+
|
| 32 |
+
Because no answer token is ever written back into the prompt, and the softmax support *is*
|
| 33 |
+
your option list, an answer outside the declared options isn't just improbable β it's
|
| 34 |
+
outside the sample space. Expected calibration error is 2.3% (4th lowest of 73 models up to
|
| 35 |
+
1B); about 1.7 GB of GPU memory in bf16, 38 ms per text question.
|
| 36 |
+
|
| 37 |
+
## How to use it
|
| 38 |
+
|
| 39 |
+
**State** β the context to classify. Plain text or JSON; non-string JSON is serialized.
|
| 40 |
+
|
| 41 |
+
**Questions** β one paragraph per question:
|
| 42 |
+
|
| 43 |
+
```
|
| 44 |
+
[choice] <optional instructions>
|
| 45 |
+
option-name: description
|
| 46 |
+
another-option
|
| 47 |
+
|
| 48 |
+
[noul] <optional instructions>
|
| 49 |
+
yes: what "yes" means β both lines optional
|
| 50 |
+
no: what "no" means
|
| 51 |
+
|
| 52 |
+
[score] <optional instructions>
|
| 53 |
+
lowest level
|
| 54 |
+
...
|
| 55 |
+
highest level
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
**Prompt protocol** (*Advanced*) β `text` renders options as `key: description` (the model
|
| 59 |
+
card's usage path); `vision` is the Decision Index vision-board protocol, with option
|
| 60 |
+
descriptions alone and no default instructions. Rendering only β either works with or
|
| 61 |
+
without an image attached.
|
| 62 |
+
|
| 63 |
+
A question row longer than 32,768 tokens, or with more than 255 options, is **refused,
|
| 64 |
+
never truncated** (training rows were at most 16,384 tokens).
|
| 65 |
+
|
| 66 |
+
## Implementation notes
|
| 67 |
+
|
| 68 |
+
- The app uses the authors' own `decision_model` package, loaded straight from the
|
| 69 |
+
checkpoint snapshot's `source/src` (added to `sys.path`), via
|
| 70 |
+
`DecisionModel.from_pretrained(..., device="cuda")`.
|
| 71 |
+
- **Attention check deferred.** `DecisionModel.__init__` ends with a real
|
| 72 |
+
`check_attention()` forward pass that verifies the checkpoint's non-causal full
|
| 73 |
+
attention on the mask that actually reaches a full-attention layer β impossible at
|
| 74 |
+
module scope on ZeroGPU, where the main process has no GPU. The check (plus the
|
| 75 |
+
authors' `warmup()`, which compiles the Gated DeltaNet Triton kernels) therefore runs
|
| 76 |
+
on the first GPU call of each worker, unchanged and un-suppressed; it raises and the
|
| 77 |
+
app refuses to serve if the running attention is not the checkpoint's
|
| 78 |
+
`noncausal_full_attention`.
|
| 79 |
+
- The full-attention layers see the whole row (padding-masked only) while the
|
| 80 |
+
Gated DeltaNet linear-attention layers keep their causal recurrence; the checkpoint's
|
| 81 |
+
fitted temperature (1.4467) is applied inside the package and is never overridden.
|
| 82 |
+
- `flash-linear-attention` 0.5.2 is installed so the 18 Gated DeltaNet layers get their
|
| 83 |
+
Triton kernels; `transformers` is pinned to 5.22.1, inside the authors' tested range
|
| 84 |
+
(5.7.0, 5.13.1, 5.22.1 with torch 2.11.0).
|
| 85 |
+
- Images are placed before the state, aspect ratio kept, sides multiples of 32 px,
|
| 86 |
+
at most 1.6 MP (the Decision Index vision board cap), exactly as the package does.
|
| 87 |
+
- Question IDs are derived from the instructions' first words; the model never sees IDs.
|
| 88 |
+
|
| 89 |
+
Weights and inference code: Apache-2.0 (Illuin Technology). Space code: Apache-2.0.
|
| 90 |
+
|
| 91 |
+
### Example images
|
| 92 |
+
|
| 93 |
+
`cat_tabby.jpg` and `sign_beach.jpg` are from
|
| 94 |
+
[`linoyts/repo-to-space-example-inputs`](https://huggingface.co/datasets/linoyts/repo-to-space-example-inputs)
|
| 95 |
+
(CC0, no attribution required). The questions beside them were written against those exact
|
| 96 |
+
photos.
|
app.py
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Ivonnet-0.8B β typed decisions with calibrated probabilities, no decoding.
|
| 2 |
+
|
| 3 |
+
Illuin's Ivonnet-0.8B does not generate text. You hand the model a *state* β plain text,
|
| 4 |
+
JSON, an image, or any combination β plus a set of typed questions β `choice` (pick one of
|
| 5 |
+
up to 255 named options), `noul` (yes/no), or `score` (an ordered scale) β and it returns
|
| 6 |
+
a calibrated probability for every option, read in a single forward pass: the hidden
|
| 7 |
+
state at the generation position goes through a linear readout over 255 single-token
|
| 8 |
+
answer codes, softmaxed at the checkpoint's fitted temperature.
|
| 9 |
+
|
| 10 |
+
This Space wraps [`illuin/Ivonnet-0.8B`](https://huggingface.co/illuin/Ivonnet-0.8B)
|
| 11 |
+
(0.85 B params on a Qwen3.5-0.8B hybrid-attention backbone β 18 Gated DeltaNet
|
| 12 |
+
linear-attention layers + 6 non-causal full-attention layers β bf16, ~1.7 GB) with the
|
| 13 |
+
authors' own `decision_model` package loaded straight from the checkpoint's `source/`
|
| 14 |
+
directory, at the fitted temperature 1.447 saved in `decision_config.json`.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import time
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
|
| 24 |
+
|
| 25 |
+
import spaces # noqa: E402 (must precede any CUDA-touching import)
|
| 26 |
+
|
| 27 |
+
import gradio as gr
|
| 28 |
+
|
| 29 |
+
MODEL_ID = "illuin/Ivonnet-0.8B"
|
| 30 |
+
|
| 31 |
+
# ---------------------------------------------------------------------------------------------
|
| 32 |
+
# Model β the authors' own loading recipe, verbatim except for one deferral. The weights
|
| 33 |
+
# are fetched from the Hub by the Space itself; the checkpoint ships its inference package
|
| 34 |
+
# in `source/src`, which goes on sys.path.
|
| 35 |
+
#
|
| 36 |
+
# DecisionModel.__init__ ends with `self.attention_check = self.check_attention()` β REAL
|
| 37 |
+
# forward passes that verify the non-causal full attention on the mask that actually
|
| 38 |
+
# reaches a full-attention layer. ZeroGPU's main process has no GPU, so the check cannot
|
| 39 |
+
# run at module scope: it is deferred to the first @spaces.GPU call (see _ensure_ready),
|
| 40 |
+
# where it runs unchanged, together with the authors' warmup(). The attention SETUP itself
|
| 41 |
+
# (the mask mapping on transformers >= 5.13, `is_causal = False` on the full-attention
|
| 42 |
+
# layers) happens in __init__ and needs no GPU.
|
| 43 |
+
# ---------------------------------------------------------------------------------------------
|
| 44 |
+
from huggingface_hub import snapshot_download # noqa: E402
|
| 45 |
+
|
| 46 |
+
CHECKPOINT = Path(snapshot_download(MODEL_ID))
|
| 47 |
+
sys.path.insert(0, str(CHECKPOINT / "source" / "src"))
|
| 48 |
+
|
| 49 |
+
from decision_model import DecisionModel, InputTooLong, UnsupportedQuestion # noqa: E402
|
| 50 |
+
|
| 51 |
+
_REAL_CHECK_ATTENTION = DecisionModel.check_attention
|
| 52 |
+
DecisionModel.check_attention = lambda self: {"deferred": "runs on the first GPU call"}
|
| 53 |
+
try:
|
| 54 |
+
MODEL = DecisionModel.from_pretrained(CHECKPOINT, device="cuda")
|
| 55 |
+
finally:
|
| 56 |
+
DecisionModel.check_attention = _REAL_CHECK_ATTENTION
|
| 57 |
+
|
| 58 |
+
CALIBRATED_TEMPERATURE = MODEL.temperature # fitted on held-out data; must not be overridden
|
| 59 |
+
|
| 60 |
+
_READY = {"ok": False} # per-worker flag: flips on the first @spaces.GPU call
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _ensure_ready() -> None:
|
| 64 |
+
"""Once per worker: run the model's own attention check and its warmup, on the GPU.
|
| 65 |
+
|
| 66 |
+
`check_attention` refuses to serve if the full-attention layers see anything but the
|
| 67 |
+
padding-only mask β the same guarantee the package enforces at load time everywhere
|
| 68 |
+
else. `warmup` compiles and tunes the Gated DeltaNet Triton kernels for the request
|
| 69 |
+
shapes, exactly as the authors' server does at startup.
|
| 70 |
+
"""
|
| 71 |
+
if _READY["ok"]:
|
| 72 |
+
return
|
| 73 |
+
MODEL.attention_check = MODEL.check_attention()
|
| 74 |
+
MODEL.warmup()
|
| 75 |
+
_READY["ok"] = True
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _gpu_duration(*_args, **_kwargs) -> int:
|
| 79 |
+
"""A cold worker pays weight streaming + the attention check + kernel warmup; a warm
|
| 80 |
+
worker only pays the forward pass. Duration follows the call, not the worst case."""
|
| 81 |
+
return 150 if not _READY["ok"] else 40
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# ---------------------------------------------------------------------------------------------
|
| 85 |
+
# Question-block DSL: one paragraph per question, glued into a single textbox so the UI
|
| 86 |
+
# stays one input for the questions dict, in author order. Every block:
|
| 87 |
+
#
|
| 88 |
+
# [choice] <optional instructions> β question line: [type] then instructions
|
| 89 |
+
# option-name: description β one line per option (description optional)
|
| 90 |
+
# option-name
|
| 91 |
+
# ...
|
| 92 |
+
#
|
| 93 |
+
# [score] <optional instructions>
|
| 94 |
+
# level 1 description
|
| 95 |
+
# level 2 description
|
| 96 |
+
# ...
|
| 97 |
+
#
|
| 98 |
+
# [noul] <optional instructions>
|
| 99 |
+
# (optionally `yes: ...` / `no: ...` description lines)
|
| 100 |
+
#
|
| 101 |
+
# Question IDs are derived from the instructions' first words (the model never sees IDs,
|
| 102 |
+
# only the rendered question), and are made unique if two questions share a prefix.
|
| 103 |
+
# ---------------------------------------------------------------------------------------------
|
| 104 |
+
def parse_questions(block_text: str) -> dict:
|
| 105 |
+
"""Convert the question textbox into the decision_model `questions` dict (in order)."""
|
| 106 |
+
questions: dict = {}
|
| 107 |
+
for para in block_text.replace("\r\n", "\n").strip().split("\n\n"):
|
| 108 |
+
lines = [ln.strip() for ln in para.split("\n") if ln.strip()]
|
| 109 |
+
if not lines:
|
| 110 |
+
continue
|
| 111 |
+
head = lines[0]
|
| 112 |
+
kind = next((k for k in ("choice", "noul", "score") if head.startswith(f"[{k}]")), None)
|
| 113 |
+
if kind is None:
|
| 114 |
+
raise ValueError(
|
| 115 |
+
f"Every question block must start with [choice], [noul] or [score] β got: {head!r}"
|
| 116 |
+
)
|
| 117 |
+
instructions = head[len(f"[{kind}]"):].strip() or None
|
| 118 |
+
body = lines[1:]
|
| 119 |
+
if kind == "choice":
|
| 120 |
+
criteria: dict = {}
|
| 121 |
+
for ln in body:
|
| 122 |
+
if ":" in ln:
|
| 123 |
+
name, desc = ln.split(":", 1)
|
| 124 |
+
else:
|
| 125 |
+
name, desc = ln, None
|
| 126 |
+
name = name.strip()
|
| 127 |
+
if not name:
|
| 128 |
+
raise ValueError(f"A choice option line has no option name: {ln!r}")
|
| 129 |
+
criteria[name] = desc.strip() if desc else None
|
| 130 |
+
if not criteria:
|
| 131 |
+
raise ValueError(f"A [choice] question needs at least one option line: {head!r}")
|
| 132 |
+
question = {"type": "choice", "criteria": criteria, "instructions": instructions}
|
| 133 |
+
elif kind == "score":
|
| 134 |
+
levels = [ln for ln in body]
|
| 135 |
+
if len(levels) < 2:
|
| 136 |
+
raise ValueError(f"A [score] question needs at least two level lines: {head!r}")
|
| 137 |
+
question = {"type": "score", "criteria": levels, "instructions": instructions}
|
| 138 |
+
else: # noul
|
| 139 |
+
criteria = {"true": None, "false": None}
|
| 140 |
+
for ln in body:
|
| 141 |
+
if ln[:3].lower() == "yes":
|
| 142 |
+
criteria["true"] = ln[3:].lstrip(":- ").strip() or None
|
| 143 |
+
elif ln[:2].lower() == "no":
|
| 144 |
+
criteria["false"] = ln[2:].lstrip(":- ").strip() or None
|
| 145 |
+
else:
|
| 146 |
+
raise ValueError(
|
| 147 |
+
f"A [noul] block may only carry 'yes: ...' / 'no: ...' description "
|
| 148 |
+
f"lines: {ln!r}"
|
| 149 |
+
)
|
| 150 |
+
question = {"type": "noul", "criteria": criteria, "instructions": instructions}
|
| 151 |
+
# Stable, unique-ish IDs from the instructions (or the type, if no instructions).
|
| 152 |
+
base = " ".join((instructions or kind).split()[:3]).lower()
|
| 153 |
+
qid = "".join(ch if ch.isalnum() else "_" for ch in base).strip("_") or kind
|
| 154 |
+
while qid in questions:
|
| 155 |
+
qid = f"{qid}_"
|
| 156 |
+
questions[qid] = question
|
| 157 |
+
if not questions:
|
| 158 |
+
raise ValueError("Define at least one question block.")
|
| 159 |
+
return questions
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _fmt_pct(p: float) -> str:
|
| 163 |
+
return f"{p * 100:.1f}%"
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def _bar(p: float, width: int = 26) -> str:
|
| 167 |
+
filled = int(round(p * width))
|
| 168 |
+
return "β" * filled + "β" * max(0, width - filled)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def render_answers(answers: dict, questions: dict) -> str:
|
| 172 |
+
"""Render the decisions as Markdown verdict cards, one section per question."""
|
| 173 |
+
out: list[str] = []
|
| 174 |
+
for qid, ans in answers.items():
|
| 175 |
+
q = questions[qid]
|
| 176 |
+
kind = ans["type"]
|
| 177 |
+
instructions = q.get("instructions") or "Choose the best matching option."
|
| 178 |
+
out.append(f"### {instructions}")
|
| 179 |
+
if kind == "noul":
|
| 180 |
+
p_true = ans["noul"]
|
| 181 |
+
verdict = "**YES**" if p_true >= 0.5 else "**NO**"
|
| 182 |
+
out.append(f"{verdict} β P(true) = **{p_true:.3f}**\n")
|
| 183 |
+
out.append(f"`{_bar(p_true)}` yes {_fmt_pct(p_true)} Β· no {_fmt_pct(1 - p_true)}\n")
|
| 184 |
+
elif kind == "choice":
|
| 185 |
+
probs = ans["probabilities"]
|
| 186 |
+
best = ans["choice"]
|
| 187 |
+
out.append(f"**{best}**\n")
|
| 188 |
+
ordered = sorted(probs.items(), key=lambda kv: kv[1], reverse=True)
|
| 189 |
+
for name, p in ordered:
|
| 190 |
+
mark = " β" if name == best else ""
|
| 191 |
+
out.append(f"- `{_bar(p)}` {_fmt_pct(p)} {name}{mark}")
|
| 192 |
+
out.append("")
|
| 193 |
+
else: # score: levels are the question's criteria list, keyed "0", "1", ...
|
| 194 |
+
levels = list(q["criteria"])
|
| 195 |
+
probs = ans["probabilities"]
|
| 196 |
+
score = ans["score"]
|
| 197 |
+
best_ix = max(probs, key=probs.get)
|
| 198 |
+
out.append(
|
| 199 |
+
f"expected level **{score:.2f}** β most likely `{levels[int(best_ix)]}`\n"
|
| 200 |
+
)
|
| 201 |
+
ranked = sorted(probs.items(), key=lambda kv: kv[1], reverse=True)
|
| 202 |
+
for ix, p in ranked:
|
| 203 |
+
out.append(f"- `{_bar(p)}` {_fmt_pct(p)} level {ix}: {levels[int(ix)]}")
|
| 204 |
+
out.append("")
|
| 205 |
+
return "\n".join(out)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
# ---------------------------------------------------------------------------------------------
|
| 209 |
+
# Inference
|
| 210 |
+
# ---------------------------------------------------------------------------------------------
|
| 211 |
+
@spaces.GPU(duration=_gpu_duration)
|
| 212 |
+
def decide(state: str, questions_text: str, image=None, style: str = "text") -> tuple[str, str]:
|
| 213 |
+
"""Answer typed decision questions about a state (and optional image) in one forward pass.
|
| 214 |
+
|
| 215 |
+
Args:
|
| 216 |
+
state: The context to classify β plain text or JSON. Questions are answered from it.
|
| 217 |
+
questions_text: Question blocks, one paragraph per question. A block starts with
|
| 218 |
+
`[choice]`/`[noul]`/`[score]` plus optional instructions, then one line per
|
| 219 |
+
option (choice: `name: description`), per level (score), or optional
|
| 220 |
+
`yes:`/`no:` descriptions (noul).
|
| 221 |
+
image: Optional image. Placed before the state; every question sees it.
|
| 222 |
+
style: Prompt protocol β "text" (options as `key: description`, the model card's
|
| 223 |
+
usage path) or "vision" (the Decision Index vision board protocol: option
|
| 224 |
+
descriptions alone, no default instructions).
|
| 225 |
+
|
| 226 |
+
Returns:
|
| 227 |
+
Markdown verdict cards plus the raw decisions-API JSON.
|
| 228 |
+
"""
|
| 229 |
+
if not (state and state.strip()):
|
| 230 |
+
raise gr.Error("Give the decision a state β the text (or JSON) context to classify.")
|
| 231 |
+
# `state` accepts text or any JSON value; hand the model the parsed object when it is one.
|
| 232 |
+
try:
|
| 233 |
+
parsed = json.loads(state)
|
| 234 |
+
except (json.JSONDecodeError, ValueError):
|
| 235 |
+
parsed = state
|
| 236 |
+
if not isinstance(parsed, (dict, list)):
|
| 237 |
+
parsed = state
|
| 238 |
+
try:
|
| 239 |
+
questions = parse_questions(questions_text or "")
|
| 240 |
+
except ValueError as exc:
|
| 241 |
+
raise gr.Error(str(exc)) from None
|
| 242 |
+
|
| 243 |
+
try:
|
| 244 |
+
_ensure_ready()
|
| 245 |
+
except RuntimeError as exc: # the model's own attention check refused to serve
|
| 246 |
+
raise gr.Error(f"attention check failed: {exc}") from None
|
| 247 |
+
|
| 248 |
+
images = [image] if image is not None else ()
|
| 249 |
+
t0 = time.perf_counter()
|
| 250 |
+
try:
|
| 251 |
+
result = MODEL.decide(parsed, questions, images=images, style=style)
|
| 252 |
+
except (InputTooLong, UnsupportedQuestion) as exc:
|
| 253 |
+
raise gr.Error(str(exc)) from None
|
| 254 |
+
elapsed = time.perf_counter() - t0
|
| 255 |
+
|
| 256 |
+
answers = result["answers"]
|
| 257 |
+
header = (
|
| 258 |
+
f"### {len(answers)} question{'s' if len(answers) != 1 else ''} Β· {style} protocol Β· "
|
| 259 |
+
f"**{elapsed * 1000:.0f} ms** Β· {result['usage']['input_tokens']:,} input tokens"
|
| 260 |
+
)
|
| 261 |
+
cards = render_answers(answers, questions)
|
| 262 |
+
raw = json.dumps(result, indent=2, ensure_ascii=False)
|
| 263 |
+
return f"{header}\n\n{cards}", raw
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
# ---------------------------------------------------------------------------------------------
|
| 267 |
+
# Default inputs β the canonical example is the model card's own usage sample
|
| 268 |
+
# ---------------------------------------------------------------------------------------------
|
| 269 |
+
CANONICAL_STATE = "My integration keeps failing with a 401."
|
| 270 |
+
|
| 271 |
+
CANONICAL_QUESTIONS = """[choice] Which team should handle this request?
|
| 272 |
+
billing: Charges and refunds
|
| 273 |
+
support: Technical integration errors
|
| 274 |
+
sales: Questions about buying a product
|
| 275 |
+
|
| 276 |
+
[noul] Is the customer blocked?"""
|
| 277 |
+
|
| 278 |
+
TICKET_STATE = """{"ticket_id": "T-4187", "channel": "email", "priority": "P2",
|
| 279 |
+
"message": "I was charged twice for my March invoice and the refund still hasn't landed.",
|
| 280 |
+
"plan": "Pro monthly", "previous_tickets": 3, "last_refund_request_days_ago": 12}"""
|
| 281 |
+
|
| 282 |
+
TICKET_QUESTIONS = """[choice] Which team should handle this ticket?
|
| 283 |
+
billing: Charges, invoices and refunds
|
| 284 |
+
support: Technical defects and bug reports
|
| 285 |
+
sales: Plan upgrades and new purchases
|
| 286 |
+
|
| 287 |
+
[noul] Does the customer mention any technical error or broken feature?
|
| 288 |
+
|
| 289 |
+
[score] How urgent does the customer's tone sound?
|
| 290 |
+
routine
|
| 291 |
+
elevated
|
| 292 |
+
urgent"""
|
| 293 |
+
|
| 294 |
+
CAT_STATE = (
|
| 295 |
+
"The customer sent this photo with their message: 'Is this thing safe to pet? It has been "
|
| 296 |
+
"staring at me from under the couch for an hour.'"
|
| 297 |
+
)
|
| 298 |
+
CAT_QUESTIONS = """[choice] What animal is in the photo?
|
| 299 |
+
cat
|
| 300 |
+
dog
|
| 301 |
+
rabbit
|
| 302 |
+
ferret
|
| 303 |
+
|
| 304 |
+
[noul] Are the animal's eyes open?
|
| 305 |
+
|
| 306 |
+
[score] How calm does the animal look?
|
| 307 |
+
agitated
|
| 308 |
+
alert
|
| 309 |
+
relaxed
|
| 310 |
+
asleep"""
|
| 311 |
+
|
| 312 |
+
SIGN_STATE = (
|
| 313 |
+
"A beach-scene photo crawled by our content pipeline. Read it as the customers see it and "
|
| 314 |
+
"classify the shot for the storefront."
|
| 315 |
+
)
|
| 316 |
+
SIGN_QUESTIONS = """[choice] What does the letter-board sign in the image say?
|
| 317 |
+
SUMMER TIME
|
| 318 |
+
BEACH DAY
|
| 319 |
+
SUNSET HOUR
|
| 320 |
+
GOOD VIBES
|
| 321 |
+
|
| 322 |
+
[noul] Does the image contain a film camera?
|
| 323 |
+
|
| 324 |
+
[score] How prominent is the ocean in the frame?
|
| 325 |
+
not visible
|
| 326 |
+
distant haze
|
| 327 |
+
clear midground
|
| 328 |
+
dominant"""
|
| 329 |
+
|
| 330 |
+
CSS = """
|
| 331 |
+
#col-container { max-width: 1150px; margin: 0 auto; }
|
| 332 |
+
.dark .gradio-container { color: var(--body-text-color); }
|
| 333 |
+
"""
|
| 334 |
+
|
| 335 |
+
with gr.Blocks(title="ivonnet", fill_width=True) as demo:
|
| 336 |
+
with gr.Column(elem_id="col-container"):
|
| 337 |
+
gr.Markdown(
|
| 338 |
+
"# Ivonnet-0.8B\n"
|
| 339 |
+
"Illuin's small **typed decision** model: give it a state and typed questions β "
|
| 340 |
+
"**choice** (pick one of up to 255 options), **noul** (yes / no), **score** (an "
|
| 341 |
+
"ordered scale) β and it returns a **calibrated probability** for every option in "
|
| 342 |
+
"**one forward pass, zero generated tokens**, read through a 255-answer-code "
|
| 343 |
+
"linear readout at the fitted temperature 1.447.\n\n"
|
| 344 |
+
"0.85 B params on a Qwen3.5-0.8B hybrid-attention backbone (18 Gated DeltaNet "
|
| 345 |
+
"linear-attention layers + 6 non-causal full-attention layers), bf16 (~1.7 GB), "
|
| 346 |
+
"38 ms per text question. [model card](https://huggingface.co/illuin/Ivonnet-0.8B)"
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
with gr.Row():
|
| 350 |
+
with gr.Column(scale=3):
|
| 351 |
+
state_input = gr.Textbox(
|
| 352 |
+
value=CANONICAL_STATE,
|
| 353 |
+
label="State",
|
| 354 |
+
lines=4,
|
| 355 |
+
placeholder="The context to classify β plain text or JSON.",
|
| 356 |
+
info="Non-string states are serialized as JSON. Put everything the questions "
|
| 357 |
+
"need in here β questions never see each other, only the state.",
|
| 358 |
+
)
|
| 359 |
+
img_input = gr.Image(
|
| 360 |
+
type="pil",
|
| 361 |
+
label="Image (optional)",
|
| 362 |
+
height=280,
|
| 363 |
+
)
|
| 364 |
+
with gr.Column(scale=4):
|
| 365 |
+
questions_input = gr.Code(
|
| 366 |
+
value=CANONICAL_QUESTIONS,
|
| 367 |
+
language=None,
|
| 368 |
+
label="Questions",
|
| 369 |
+
lines=18,
|
| 370 |
+
buttons=[],
|
| 371 |
+
)
|
| 372 |
+
gr.Markdown(
|
| 373 |
+
"**Questions** β one paragraph per question. First line: `[choice]` / `[noul]` / "
|
| 374 |
+
"`[score]` + optional instructions. Then: choice β one `option: description` per "
|
| 375 |
+
"line (description optional); score β one level per line (lowest first); noul β "
|
| 376 |
+
"optional `yes:`/`no:` descriptions. **Image** is placed before the state; every "
|
| 377 |
+
"question sees it (aspect ratio kept, sides multiples of 32 px). A question row "
|
| 378 |
+
"longer than 32,768 tokens or with more than 255 options is refused, never "
|
| 379 |
+
"truncated."
|
| 380 |
+
)
|
| 381 |
+
run = gr.Button("Decide", variant="primary")
|
| 382 |
+
|
| 383 |
+
verdict = gr.Markdown("Verdict cards appear here.")
|
| 384 |
+
with gr.Accordion("Raw decisions (API JSON)", open=False):
|
| 385 |
+
raw_json = gr.Code(language="json", label="Response", buttons=["copy"], lines=14)
|
| 386 |
+
|
| 387 |
+
with gr.Accordion("Advanced", open=False):
|
| 388 |
+
style_input = gr.Radio(
|
| 389 |
+
choices=["text", "vision"],
|
| 390 |
+
value="text",
|
| 391 |
+
label="Prompt protocol",
|
| 392 |
+
info="'text' renders options as `key: description` (the model card's usage "
|
| 393 |
+
"path); 'vision' is the Decision Index vision-board protocol β option "
|
| 394 |
+
"descriptions alone and no default instructions. This is prompt "
|
| 395 |
+
"rendering only; it is independent of whether an image is attached.",
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
gr.Examples(
|
| 399 |
+
examples=[
|
| 400 |
+
[CANONICAL_STATE, CANONICAL_QUESTIONS],
|
| 401 |
+
[TICKET_STATE, TICKET_QUESTIONS],
|
| 402 |
+
],
|
| 403 |
+
inputs=[state_input, questions_input],
|
| 404 |
+
outputs=[verdict, raw_json],
|
| 405 |
+
fn=decide,
|
| 406 |
+
cache_examples=True,
|
| 407 |
+
cache_mode="lazy",
|
| 408 |
+
label="Text examples β the model card's own usage sample, then a JSON ticket",
|
| 409 |
+
)
|
| 410 |
+
gr.Examples(
|
| 411 |
+
examples=[
|
| 412 |
+
[CAT_STATE, CAT_QUESTIONS, "examples/cat_tabby.jpg"],
|
| 413 |
+
[SIGN_STATE, SIGN_QUESTIONS, "examples/sign_beach.jpg"],
|
| 414 |
+
],
|
| 415 |
+
inputs=[state_input, questions_input, img_input],
|
| 416 |
+
outputs=[verdict, raw_json],
|
| 417 |
+
fn=decide,
|
| 418 |
+
cache_examples=True,
|
| 419 |
+
cache_mode="lazy",
|
| 420 |
+
label="Vision examples β photos rated by the typed questions",
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
run.click(
|
| 424 |
+
fn=decide,
|
| 425 |
+
inputs=[state_input, questions_input, img_input, style_input],
|
| 426 |
+
outputs=[verdict, raw_json],
|
| 427 |
+
api_name="decide",
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
demo.queue(max_size=32)
|
| 432 |
+
demo.launch(mcp_server=True, ssr_mode=False, theme=gr.themes.Citrus(), css=CSS)
|
examples/cat_tabby.jpg
ADDED
|
Git LFS Details
|
examples/sign_beach.jpg
ADDED
|
Git LFS Details
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# torch / gradio / spaces / huggingface_hub are preinstalled and platform-managed on the
|
| 2 |
+
# ZeroGPU image -- do NOT pin them here.
|
| 3 |
+
# transformers pinned inside the checkpoint's tested range (>=5.7,<6; tested 5.7.0, 5.13.1
|
| 4 |
+
# and 5.22.1) β the model's own attention check refuses to serve outside its mask contract.
|
| 5 |
+
transformers==5.22.1
|
| 6 |
+
safetensors
|
| 7 |
+
pillow
|
| 8 |
+
# real Triton kernels for Qwen3.5's Gated DeltaNet linear-attention layers; without them
|
| 9 |
+
# 3 of every 4 layers run on a much slower pure-torch fallback
|
| 10 |
+
flash-linear-attention==0.5.2
|