ive-4b / app.py
multimodalart's picture
multimodalart HF Staff
Upload app.py with huggingface_hub
6d8527c verified
Raw History Blame Contribute Delete
13 kB
import os
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import spaces # noqa: E402 (must precede torch)
import html # noqa: E402
import json # noqa: E402
import time # noqa: E402
import gradio as gr # noqa: E402
import torch # noqa: E402
from decision_model import DecisionModel, InputTooLong, UnsupportedQuestion # noqa: E402
MODEL_ID = "illuin/IVE-4B"
MAX_IMAGES = 4
MAX_QUESTIONS = 32
# The authors' DecisionModel verifies at load time (with two short forward passes) that the
# full-attention layers run non-causally. ZeroGPU has no GPU attached at module scope, so the
# check is deferred to the first GPU call of each worker (same check, same RuntimeError).
_check_attention = DecisionModel.check_attention
DecisionModel.check_attention = lambda self: {"deferred": True}
model = DecisionModel.from_pretrained(MODEL_ID, device="cuda")
DecisionModel.check_attention = _check_attention
model.name = MODEL_ID
_checked = {"done": False}
def _parse_questions(questions):
try:
qs = json.loads(questions) if isinstance(questions, str) else questions
except json.JSONDecodeError as e:
raise gr.Error(f"Questions must be valid JSON: {e}")
if isinstance(qs, dict) and isinstance(qs.get("questions"), dict):
qs = qs["questions"]
if not isinstance(qs, dict) or not qs:
raise gr.Error('Questions must be a JSON object: {"id": {"type": "choice"|"noul", ...}}')
if len(qs) > MAX_QUESTIONS:
raise gr.Error(f"At most {MAX_QUESTIONS} questions per request in this demo.")
for qid, q in qs.items():
if not isinstance(q, dict):
raise gr.Error(f"Question {qid!r} must be an object.")
return qs
def _parse_state(state):
st = state or ""
if isinstance(st, str) and st.strip()[:1] in ("{", "["):
try:
return json.loads(st)
except json.JSONDecodeError:
return st
return st
def _image_paths(images):
paths = []
for it in images or []:
if isinstance(it, (list, tuple)):
it = it[0]
if isinstance(it, dict):
it = it.get("path") or it.get("name")
if it:
paths.append(str(it))
return paths
def _render(qs, answers):
cards = []
for qid, q in qs.items():
a = answers[qid]
if a["type"] == "noul":
p = a["noul"]
rows = [("true", p), ("false", 1 - p)]
best = "true" if p >= 0.5 else "false"
headline = f"P(true) = {p:.3f}"
else:
probs = a["probabilities"]
rows = list(probs.items())
best = a.get("choice") or max(probs, key=probs.get)
if a["type"] == "score":
headline = f"score {a['score']:.2f}"
else:
headline = f"{html.escape(str(best))} · {probs[best]:.3f}"
bars = "".join(
f"<div class='ive-row'><span class='ive-name{' ive-best' if n == best else ''}'>{html.escape(str(n))}</span>"
f"<span class='ive-bar'><span style='width:{max(p, 0.003) * 100:.1f}%'></span></span>"
f"<span class='ive-p'>{p:.3f}</span></div>"
for n, p in rows
)
instr = q.get("instructions") or ""
cards.append(
f"<div class='ive-card'><div class='ive-head'><b>{html.escape(str(qid))}</b>"
f"<span class='ive-type'>{a['type']}</span><span class='ive-hl'>{headline}</span></div>"
f"<div class='ive-q'>{html.escape(str(instr))}</div>{bars}</div>"
)
return "<div class='ive-wrap'>" + "".join(cards) + "</div>"
def _gpu_duration(state, questions, images=None, *args, **kwargs):
"""Measured on ZeroGPU: text ~0.1-0.3 s; one ~2 MP page ~1 s warm, ~9 s on the first
(kernel-compiling) call. Budget per image for cold kernel compilation."""
n = len(_image_paths(images)[:MAX_IMAGES])
return 8 if n == 0 else min(30, 8 + 4 * n)
@spaces.GPU(duration=_gpu_duration)
def decide(state: str, questions: str, images: list | None = None):
"""Answer typed decision questions about a state with calibrated probabilities (IVE-4B).
Args:
state: The state to decide about: plain text or JSON. May be empty when images are given.
questions: Questions as JSON (Decision Index /v1/systemone format): a map of
id -> {"type": "choice" | "noul", "instructions": str, "criteria": {...}}.
choice criteria map option keys to descriptions; noul criteria optionally give
{"true": ..., "false": ...} descriptions.
images: Optional list of image file paths (up to 4) shown before the state.
Returns:
An HTML summary of the probabilities and the /v1/systemone-shaped JSON response.
"""
qs = _parse_questions(questions)
st = _parse_state(state)
paths = _image_paths(images)[:MAX_IMAGES]
if not paths and (st == "" or st is None):
raise gr.Error("Provide a state (text or JSON) and/or at least one image.")
torch.backends.cuda.enable_cudnn_sdp(False) # as in training
if not _checked["done"]:
model.attention_check = model.check_attention()
print("attention check:", model.attention_check, flush=True)
_checked["done"] = True
t0 = time.perf_counter()
try:
out = model.decide(st, qs, images=paths)
except (InputTooLong, UnsupportedQuestion) as e:
raise gr.Error(str(e))
secs = time.perf_counter() - t0
out["timing"] = {"seconds": round(secs, 3), **{k: (round(v, 4) if isinstance(v, float) else v)
for k, v in model.last_timing.items()}}
print(f"decide: {len(qs)} q, {len(paths)} img, {out['usage']['input_tokens']} tok, {secs:.2f}s", flush=True)
return _render(qs, out["answers"]), out
def _j(x):
return json.dumps(x, indent=2, ensure_ascii=False)
# Example from the model card.
EX_SUPPORT_STATE = "My integration keeps failing with a 401."
EX_SUPPORT_Q = {
"team": {"type": "choice", "instructions": "Which team should handle this request?",
"criteria": {"billing": "Charges and refunds",
"support": "Technical integration errors",
"sales": "Questions about buying a product"}},
"blocked": {"type": "noul", "instructions": "Is the customer blocked?"},
}
EX_TICKET_STATE = _j({
"ticket": "Hi, I was charged twice for my March invoice (INV-2291). Please refund the duplicate "
"charge. If this isn't fixed this week I'll move my team to another provider.",
"plan": "Business", "seats": 40, "customer_since": "2021-06",
})
EX_TICKET_Q = {
"team": {"type": "choice", "instructions": "Which team should handle this ticket?",
"criteria": {"billing": "Payments, invoices, refunds", "technical": "Bugs and outages",
"account": "Login, profile, plan changes", "sales": "New plans and upgrades"}},
"churn_risk": {"type": "noul", "instructions": "Does the customer threaten to leave?"},
"sentiment": {"type": "choice", "instructions": "What is the customer's tone?",
"criteria": {"positive": "Satisfied or friendly", "neutral": "Matter-of-fact",
"negative": "Frustrated or angry"}},
}
def _rerank_q(query):
# The page-relevance question from the model card's reranking example (ViDoRe V3).
return {"relevant": {
"type": "noul",
"instructions": f"Can the following question be answered from this page?\nQuestion: {query}",
"criteria": {"true": "Yes, the page contains the information needed to answer it",
"false": "No, the page does not contain that information"}}}
EX_VACANCY_Q = {
**_rerank_q("Did the Netherlands have a higher job vacancy rate than Poland in 2024?"),
"highest": {"type": "choice",
"instructions": "In the chart, which Member State has the highest job vacancy rate in 2024-Q4?",
"criteria": {"NL": "Netherlands", "BE": "Belgium", "AT": "Austria", "DE": "Germany"}},
}
EX_SKILLS_Q = {
**_rerank_q("percentage of individuals with digital skills in Bulgaria"),
"country": {"type": "choice", "instructions": "Which country is this page about?",
"criteria": {"BG": "Bulgaria", "RO": "Romania", "GR": "Greece", "HR": "Croatia"}},
"gap": {"type": "noul",
"instructions": "In 2023, is Bulgaria's share of adults with basic digital skills below the EU-27 average?"},
}
CSS = """
#col-container { max-width: 1200px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
.ive-wrap { display: flex; flex-direction: column; gap: 12px; }
.ive-card { border: 1px solid var(--border-color-primary); border-radius: 10px; padding: 10px 14px; }
.ive-head { display: flex; gap: 10px; align-items: baseline; flex-wrap: wrap; }
.ive-type { font-size: 0.8em; opacity: 0.7; border: 1px solid var(--border-color-primary); border-radius: 6px; padding: 0 6px; }
.ive-hl { margin-left: auto; font-weight: 600; }
.ive-q { font-size: 0.9em; opacity: 0.8; margin: 4px 0 8px; white-space: pre-wrap; }
.ive-row { display: grid; grid-template-columns: minmax(80px, 30%) 1fr 56px; gap: 8px; align-items: center; margin: 3px 0; }
.ive-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 0.92em; }
.ive-best { font-weight: 700; }
.ive-bar { background: var(--background-fill-secondary); border-radius: 4px; height: 12px; overflow: hidden; display: block; }
.ive-bar > span { display: block; height: 100%; background: var(--color-accent); border-radius: 4px; }
.ive-p { text-align: right; font-variant-numeric: tabular-nums; font-size: 0.9em; }
"""
with gr.Blocks(title="IVE-4B") as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown(
"# IVE-4B\n"
"A **typed decision model** by Illuin Technology (fine-tuned Qwen3.5-4B). Give it a **state** "
"(text, JSON and/or document images) and **questions** — `choice` with named options or yes/no "
"`noul` — and it returns a calibrated probability for every option, read in one forward pass "
"with no text generation.\n\n"
"[Model](https://huggingface.co/illuin/IVE-4B) · "
"[Blog post](https://huggingface.co/blog/QuentinJG/ive-release) · "
"[Decision Index](https://huggingface.co/spaces/multimodalart/jev-decision-index)"
)
with gr.Row():
with gr.Column(scale=1):
state = gr.Textbox(label="State (text or JSON; may be empty with images)", lines=5,
value=EX_SUPPORT_STATE)
questions = gr.Code(label="Questions (JSON)", language="json", value=_j(EX_SUPPORT_Q),
lines=14)
images = gr.Gallery(label=f"Images (optional, up to {MAX_IMAGES})", type="filepath",
interactive=True, columns=4, height=200)
run = gr.Button("Decide", variant="primary")
with gr.Accordion("Question format", open=False):
gr.Markdown(
"- `choice`: `{\"type\": \"choice\", \"instructions\": \"...\", "
"\"criteria\": {\"key\": \"description\", ...}}` (2–255 options)\n"
"- `noul`: `{\"type\": \"noul\", \"instructions\": \"...\"}`, optionally with "
"`\"criteria\": {\"true\": \"...\", \"false\": \"...\"}`\n"
"- Each question is answered independently over the same state and images. "
"Images are kept at native resolution up to ~2.1 MP."
)
with gr.Column(scale=1):
out_html = gr.HTML(label="Answers")
out_json = gr.JSON(label="Response (/v1/systemone shape)")
run.click(decide, inputs=[state, questions, images], outputs=[out_html, out_json], api_name="decide")
gr.Examples(
label="Text examples",
examples=[
[EX_SUPPORT_STATE, _j(EX_SUPPORT_Q)],
[EX_TICKET_STATE, _j(EX_TICKET_Q)],
],
inputs=[state, questions],
outputs=[out_html, out_json],
fn=decide,
cache_examples=True,
cache_mode="lazy",
)
gr.Examples(
label="Document page examples (ViDoRe V3, CC-BY-4.0)",
examples=[
["", _j(EX_VACANCY_Q), ["examples/job_vacancies_page.jpg"]],
["", _j(EX_SKILLS_Q), ["examples/digital_skills_page.jpg"]],
],
inputs=[state, questions, images],
outputs=[out_html, out_json],
fn=decide,
cache_examples=True,
cache_mode="lazy",
)
if __name__ == "__main__":
demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)