Upload folder using huggingface_hub
Browse filesFiles changed (4)
- README.md+44-7
- app.pyAdded+102
- jev_core.pyAdded+187
- requirements.txtAdded+4
12345678910111213---title: Jev Decisionemoji: 🐠colorFrom: greencolorTo: greensdk: gradiosdk_version: 6.30.0python_version: '3.12'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950---title: JEV-9B Decision APIemoji: ⚖️colorFrom: bluecolorTo: graysdk: gradiosdk_version: 6.28.0app_file: app.pypython_version: "3.12"startup_duration_timeout: 1hpinned: false---# JEV-9B Decision APIA minimal, machine-friendly wrapper over **System 1** of[`autotrust/JEV-9B`](https://huggingface.co/autotrust/JEV-9B) — AutoTrust AI's open*decision* model (Apache-2.0), built with the Blocks-of-Experts recipe on a frozenQwen3.5-9B backbone.System 1 answers a **typed question** in a *single prefill pass* (nothing is generated)and returns a **calibrated probability distribution**:- `noul` — "Is this true?" → `[P(false), P(true)]`- `choice` — which of 2–16 options → one probability per option- `score` — where on an ordered 0–5 scale → distribution over six levels## APIA single Gradio endpoint, `/decide`, taking `kind`, `state`, `question`, `options`(comma-separated, `choice` only) and returning JSON:```json{"kind":"choice","distribution":{"a":0.53,"b":0.33,"c":0.14},"best":"a","confidence":0.53,"state_tokens":18,"truncated":false}```This Space exists to give local agents (Hermes) one clean JSON call, rather than themulti-question HTML UI of the upstream demo. Inference core (`jev_core.py`) is themodel authors' documented `transformers` + `peft` path, reused verbatim.### Provenance & limits`jev_core.py` is reused unmodified from the authors' official demo Space([`autotrust/jev-9b-decision-demo`](https://huggingface.co/spaces/autotrust/jev-9b-decision-demo)),which is Apache-2.0. Model card caveats still apply: System 1 mirrors its teacher**including its mistakes** (multi-hop reasoning, arithmetic, dates, counting, adversarialinputs), reads English best, uses the first 1,024 tokens of state, and is **not forhigh-stakes decisions** — use confidence gating and route low-confidence decisionselsewhere. Runs on ZeroGPU (`zero-a10g`).
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""JEV-9B Decision API — one clean JSON call over System 1.
Inference core (`jev_core.py`) is the model authors' documented `transformers` + `peft`path, reused verbatim from the official demo Space (Apache-2.0). This file only wraps itin a single machine-friendly Gradio endpoint (`/decide`) that returns JSON, instead of theupstream multi-question HTML UI, so a local agent can call it headlessly.
ZeroGPU rules honoured here: * `import spaces` MUST precede torch / transformers / any CUDA-touching import (jev_core imports torch, so `spaces` is imported before it). * models are placed on `cuda` at MODULE level (inside jev_core, at import) — not inside the `@spaces.GPU` function."""
import os
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")
import spaces # noqa: E402 -- MUST precede torch / transformers / any CUDA-touching import
import json # noqa: E402
import gradio as gr # noqa: E402
import jev_core as jc # noqa: E402
def _clean_options(raw) -> list: """Accept a comma/newline-separated string (or a list) -> list of option strings.""" if isinstance(raw, (list, tuple)): items = [str(o).strip() for o in raw] else: items = [o.strip() for o in str(raw or "").replace("\n", ",").split(",")] return [o for o in items if o]
@spaces.GPU(duration=45)def decide(kind: str, state: str, question: str, options: str = "") -> str: """Answer ONE typed System 1 decision; return calibrated probabilities as JSON.
kind: "noul" | "choice" | "score" state: the text to reason about (truncated to 1024 tokens, head 60% / tail 40%) question: the decision question options: comma-separated options (choice only, 2-16); ignored for noul/score """ kind = (kind or "").strip() state = (state or "").strip() question = (question or "").strip()
if kind not in jc.KINDS: return json.dumps({"error": f"kind must be one of {list(jc.KINDS)}"}) if not state: return json.dumps({"error": "state is required"}) if not question: return json.dumps({"error": "question is required"})
opts = _clean_options(options) if kind == "choice": if not 2 <= len(opts) <= 16: return json.dumps({"error": "choice needs 2-16 comma-separated options"}) if len(set(opts)) != len(opts): return json.dumps({"error": "choice options must be unique"}) else: opts = None
state_used, truncated, n_tok = jc.truncate_state(state) dist = jc.decide(kind, state_used, question, opts) best = max(dist, key=dist.get) return json.dumps( { "kind": kind, "distribution": dist, "best": best, "confidence": dist[best], "state_tokens": n_tok, "truncated": truncated, } )
with gr.Blocks(title="JEV-9B Decision API") as demo: gr.Markdown( "## JEV-9B System 1 — typed decisions in one prefill pass\n" "`noul` (yes/no) · `choice` (2–16 options) · `score` (0–5). " "Returns a calibrated probability distribution as JSON." ) with gr.Row(): kind_in = gr.Dropdown(list(jc.KINDS), value="noul", label="kind") state_in = gr.Textbox(label="state", lines=3) question_in = gr.Textbox(label="question") options_in = gr.Textbox(label="options (comma-separated; choice only)") out_json = gr.Code(label="decision JSON", language="json") btn = gr.Button("Decide", variant="primary") btn.click( decide, inputs=[kind_in, state_in, question_in, options_in], outputs=[out_json], api_name="decide", )
demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187"""JEV-9B inference core, ported 1:1 from the model authors' documented `transformers` +`peft` path (https://huggingface.co/autotrust/JEV-9B -> "Other ways to run it").
The Blocks-of-Experts architecture: * backbone = frozen Qwen3.5-9B text tower (bit-identical to the release) * System 1 = LoRA r=16 (40.1M, shipped unmerged in `adapter/`) + a 24-slot fp32 decision head (`head.safetensors`) initialised from `lm_head` verbalizer rows * System 2 = the original `lm_head`; used with the adapter off (pristine Qwen3.5-9B)
System 1 answers a typed question (`noul` yes/no, `choice` over 2-16 options, `score` on a0-5 scale) in ONE prefill pass and returns a calibrated probability distribution. Thedecision prompt follows the authors' "bare-v1" template; the head is applied to the lasttoken's post-norm hidden state, divided by the per-kind calibration temperature."""
import jsonimport os
import torchfrom huggingface_hub import hf_hub_downloadfrom peft import PeftModelfrom safetensors.torch import load_filefrom transformers import AutoModelForCausalLM, AutoTokenizer
REPO = "autotrust/JEV-9B"LETTERS = "ABCDEFGHIJKLMNOP"KINDS = ("noul", "choice", "score")MAX_STATE_TOKENS = 1024 # the authors truncate long inputs to 1,024 tokens (head 60% / tail 40%)DEVICE = os.environ.get("JEV_DEVICE", "cuda")# Optional local-dir override (used only for offline verification of the wiring)._LOCAL = os.environ.get("JEV_MODEL_PATH")
def _file(name: str) -> str: """Resolve a model-repo file to a local path, falling back to the Hub.""" if _LOCAL: p = os.path.join(_LOCAL, name) if os.path.exists(p): return p return hf_hub_download(REPO, name)
_SRC = _LOCAL or REPO
# ---------------------------------------------------------------------------# Model loading. On ZeroGPU the final `_peft.to(DEVICE)` is intercepted at# startup: tensors are packed to disk and streamed into VRAM on the first# @spaces.GPU entry, so the load cost is never paid inside a request.## Everything is built on CPU first, then moved once:# * peft's default would be `torch_device=infer_device()` -> "cuda", making# safetensors read the adapter straight onto the GPU. That bypasses the# packer and crashes the GPU-less main process ("No CUDA GPUs are# available"). `torch_device="cpu"` keeps the read on the CPU.# * one `.to(DEVICE)` at the end moves every tensor (backbone, LoRA, head)# through the standard machinery.# ---------------------------------------------------------------------------_tok = AutoTokenizer.from_pretrained(_SRC)_base = AutoModelForCausalLM.from_pretrained(_SRC, dtype=torch.bfloat16)
# Keep the adapter UNMERGED so System 2 (generation) runs with the adapter# disabled -- `with _peft.disable_adapter():` -- i.e. pristine Qwen3.5-9B._peft = PeftModel.from_pretrained(_base, _SRC, subfolder="adapter", torch_device="cpu")
# System 1 head: fp32 linear, 4096 -> 24 slots._HEAD = torch.nn.Linear(4096, 24, dtype=torch.float32)_head_sd = load_file(_file("head.safetensors"))with torch.no_grad(): _HEAD.weight.copy_(_head_sd["proj.weight"]) _HEAD.bias.copy_(_head_sd["proj.bias"])_HEAD.eval()
_JUDGE_CFG = json.load(open(_file("judge_config.json")))_CALIB = json.load(open(_file("calibration.json")))["per_kind"]SLOT_RANGES = {k: tuple(v) for k, v in _JUDGE_CFG["slots"]["ranges"].items()}TEMPERATURES = {k: float(_CALIB[k]) for k in KINDS}
# Module handles: PeftModel -> LoraModel -> Qwen3_5ForCausalLM -> Qwen3_5TextModel._CAUSAL = _peft.base_model.model # the Qwen3_5ForCausalLM with LoRA modules inside_BACKBONE = _CAUSAL.model # the text tower (LoRA active by default)
# Single move of the whole tree (backbone + LoRA + head) to the compute device._peft.to(DEVICE)_HEAD.to(DEVICE)
# ---------------------------------------------------------------------------# Prompt template -- exactly the authors' `bare-v1` decision format.# ---------------------------------------------------------------------------
def build_decision_prompt(kind: str, state: str, question: str, options) -> tuple: """Return (prompt_text, option_labels) in the authors' `bare-v1` format.""" if kind == "noul": options = ["false", "true"] elif kind == "score": options = [str(i) for i in range(6)] options = list(options) if kind == "choice": lines = [f"{LETTERS[i]}) {o}" for i, o in enumerate(options)] else: lines = options prompt = ( f"[kind] {kind}\n[state] {state}\n[question] {question}\n[options]\n" + "\n".join(lines) + "\n[decision]:" ) return prompt, options
def truncate_state(state: str) -> tuple: """Head-60% / tail-40% truncation of the state to `MAX_STATE_TOKENS` tokens.
Returns (state_used, was_truncated, n_tokens). """ ids = _tok(state, add_special_tokens=False)["input_ids"] if len(ids) <= MAX_STATE_TOKENS: return state, False, len(ids) keep_head = int(MAX_STATE_TOKENS * 0.6) keep_tail = MAX_STATE_TOKENS - keep_head return _tok.decode(ids[:keep_head] + ids[-keep_tail:], skip_special_tokens=True), True, len(ids)
def decide(kind: str, state: str, question: str, options=None) -> dict: """Run ONE System 1 typed decision; return the calibrated probability distribution.
This mirrors the model card's reference `decide()` byte for byte: one prefill pass through the backbone with the LoRA active, the 24-slot head applied to the last token's hidden state, per-kind temperature, softmax over the active slots. """ if kind not in KINDS: raise ValueError(f"unknown kind {kind!r}") if kind == "choice": if not isinstance(options, (list, tuple)) or not 2 <= len(options) <= 16: raise ValueError("`choice` needs between 2 and 16 options") if len(set(options)) != len(options): raise ValueError("`choice` options must be unique") prompt, labels = build_decision_prompt(kind, state, question, options) device = _BACKBONE.embed_tokens.weight.device # resolve inside the GPU call ids = _tok(prompt, return_tensors="pt", add_special_tokens=False).to(device) with torch.no_grad(): h = _BACKBONE(**ids).last_hidden_state[0, -1].float() z = _HEAD(h.to(_HEAD.weight.device)) # [24] fp32 logits lo = SLOT_RANGES[kind][0] z = z[lo : lo + len(labels)] / TEMPERATURES[kind] p = torch.softmax(z, dim=0) return {label: float(v) for label, v in zip(labels, p.tolist())}
def n_state_tokens(state: str) -> int: return len(_tok(state, add_special_tokens=False)["input_ids"])
# ---------------------------------------------------------------------------# System 2 -- ordinary generation from the pristine base model (adapter off).# ---------------------------------------------------------------------------
def build_escalation_prompt(state: str, question: str, options) -> str: """The model card's confidence-gated escalation prompt (System 1 -> System 2).""" opts = [str(o) for o in options] if opts == ["false", "true"]: tail = "Answer `true` or `false` on the last line." else: tail = "Options: " + "; ".join(opts) + "\nThink it through, then give exactly one option on the last line." return f"{state}\n\nQuestion: {question}\n{tail}"
def generate(state: str, question: str, options, max_new_tokens: int = 512, enable_thinking: bool = True) -> tuple: """System 2: generate a reasoned answer with the adapter OFF -- pristine Qwen3.5-9B.
Returns (text, completed): `completed` is False when generation hit the token budget mid-sentence (the model is verbose in thinking mode), which the UI needs to avoid presenting a cut-off trace as a finished answer. """ prompt = build_escalation_prompt(state, question, options) msgs = [{"role": "user", "content": prompt}] enc = _tok.apply_chat_template( msgs, add_generation_prompt=True, enable_thinking=enable_thinking, return_tensors="pt", return_dict=True, ).to(_BACKBONE.embed_tokens.weight.device) n_prompt = enc["input_ids"].shape[1] with torch.no_grad(), _peft.disable_adapter(): out = _CAUSAL.generate(**enc, max_new_tokens=int(max_new_tokens), do_sample=False) text = _tok.decode(out[0, n_prompt:], skip_special_tokens=True) completed = out.shape[1] - n_prompt < int(max_new_tokens) # stopped before the cap return text.strip(), completed1234transformers==5.16.1peft==0.21.0acceleratesafetensorsREADME.md+44-7
app.pyAdded+102
jev_core.pyAdded+187
requirements.txtAdded+4