Duplicate from Mapika/decider-2b-vision
Browse filesCo-authored-by: Mark Marosi <Mapika@users.noreply.huggingface.co>
Files changed (17)
- .gitattributesAdded+36
- README.mdAdded+92
- chat_template.jinjaAdded+154
- config.jsonAdded+105
- decider/__init__.pyAdded
- decider/engine.pyAdded+166
- decider/fp8.pyAdded+54
- decider/infer.pyAdded+187
- decider/model.pyAdded+47
- decider/prompt.pyAdded+61
- decider/vision.pyAdded+78
- decider_config.jsonAdded+1
- generation_config.jsonAdded+6
- model.safetensorsAdded+3
- processor_config.jsonAdded+61
- tokenizer.jsonAdded+3
- tokenizer_config.jsonAdded+37
123456789101112131415161718192021222324252627282930313233343536*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192---license: apache-2.0base_model: Qwen/Qwen3.5-2B-Baselanguage: [en]pipeline_tag: image-text-to-texttags: [decision-model, calibrated, structured-output, vision, one-pass]---
# decider-2b-vision: typed decisions from an image in one forward pass
The vision variant of [decider-2b](https://huggingface.co/Mapika/decider-2b) (v5 languageweights transplanted into the full Qwen3.5-2B vision-language model), fine-tuned so that animage (a photo, a diagram, a game frame) plus a text question with lettered options yields acalibrated probability over the options at a single answer slot. No generation. A 256x240 gameframe costs 64 visual tokens. Text-only questions work too, with decider-2b v5's behaviour,including its abstention handling.
**Contents:** [The decider family](#the-decider-family) · [Usage](#usage) · [Training](#training) · [Results](#results) · [Limitations](#limitations) · [Changelog](#changelog)
## The decider family
All six repositories share one interface (`decider.infer.Decider`, `POST /v1/systemone` in TypeSafe's format) and onereadout: the letter logits at an answer slot, softmaxed over the options. Pick by size and input.
| model | base | weights | use it for | numbers ||---|---|---|---|---|| [decider-2b](https://huggingface.co/Mapika/decider-2b) v10 | Qwen3.5-2B-Base | 3.5 GB bf16 | the default: routing, classification, judgments, browser agents; 4 ms per request with CUDA graphs on one GPU | regression set 0.805 in-task / 0.755 held-out; live browser 93%; Bespoke suite 0.704 || [decider-4b](https://huggingface.co/Mapika/decider-4b) v1 | Qwen3.5-4B-Base | 8.4 GB bf16 | the middle point: knowledge and reasoning questions above the 2B in a dense 8.4 GB model; no RL stage | 0.834 / 0.788, above the 2B on 87 of 95 tasks; JevBench hard 0.541; Bespoke 0.757 || [decider-35b-a3b](https://huggingface.co/Mapika/decider-35b-a3b) v1 | Qwen3.5-35B-A3B-Base (3B active) | 65 GB bf16 | when accuracy is worth 3 to 4 times the cost per decision: knowledge and multi-step questions, long policies | 0.855 / 0.810, above the 2B on 93 of 95 tasks; JevBench hard 0.676; Bespoke 0.774; no RL stage || [decider-35b-a3b-nvfp4](https://huggingface.co/Mapika/decider-35b-a3b-nvfp4) | the 35B in NVFP4 | 19.6 GB | the 35B on Blackwell through vLLM or TensorRT-LLM | 1.0 to 1.5 points under bf16 on the measured fixtures || [decider-0.8b](https://huggingface.co/Mapika/decider-0.8b) | Qwen3.5-0.8B-Base | 1.4 GB bf16 | the smallest: routing, yes/no and short-state lookups within 1 to 4 points of the 2B, 1.5x faster | 0.776 / 0.707 on the single-run protocol (2B: 0.809 / 0.739) || [decider-2b-vision](https://huggingface.co/Mapika/decider-2b-vision) | Qwen3.5-2B vision-language, v5 text weights | 4.1 GB bf16 | decisions from an image plus a question; game frames | Visual7W 0.89; Breakout 41 from pixels |
Code, data registry, training scripts, the changelog and the per-version history: https://github.com/Mapika/decider.
## Usage
```pythonimport torchfrom decider.vision import VisionDecisionModelfrom decider.infer import Example, Qm = VisionDecisionModel("<this repo>", grad_ckpt=False).cuda().eval()ex = Example("This is a visual question about the image.", [Q("What is the person holding?", ["a phone", "a cup", "a book", "nothing"], 0)])inp = m.prepare([(image, ex)]) # image: PIL image, numpy array, or PNG bytes; None for text-onlyprobs = torch.softmax(m.slot_logits(inp), -1)[0, :4]```
## Training
One epoch (80k examples, 50k with images): game frames from Pong, Breakout, CliffWalking,MiniGrid and Super Mario Bros labelled by scripted policies (rare actions oversampled, plusDAgger frames from an earlier model's own play); multiple-choice image tasks from The Cauldron(A-OKVQA, AI2D, ScienceQA, IconQA, TQA, Raven, Hateful Memes); a replay of the text mixture.Then PPO from pixels on Breakout and Pong (the softmax over action options is the policy).Code: https://github.com/Mapika/decider (`decider/vision/`).
## Results
300 items per task.
| task | accuracy | ECE ||---|---|---|| Pong frames (agreement with the RAM-state teacher) | 0.96 | 0.02 || Breakout frames | 0.96 | 0.02 || Visual7W (held out) | 0.89 | 0.03 || A-OKVQA / AI2D / ScienceQA / IconQA / Raven / Hateful Memes | 0.85 / 0.93 / 0.95 / 0.94 / 0.80 / 0.80 | 0.02 to 0.07 |
Playing from pixels only (no text state), three episodes each: Breakout 41 (the RAM-stateteacher scores 22), Pong 3 (teacher 8), CliffWalking -13 (optimal), MiniGrid Empty 0.96(teacher level); held-out Freeway 0, FrozenLake 0, the harder grid worlds 0 (their scriptedteachers also score 0), Mario 1-1 315 px. The previous vision release (v4-based) scoredBreakout 16, Pong 8, Freeway 8, BabyAI-GoTo 0.30; this one trades Pong and Freeway forBreakout and for the corrected abstention behaviour.
## Limitations
Not a chat model and not a captioner: it answers lettered options at one slot. The text weights inside are decider-2b **v5**,so the text-only behaviour is that of v5 (its abstention handling, none of the v6 to v10 input shapes, calibration or browserresults); a retrain on the current text weights has not been released. Game play from pixels is measured on the Atari, MiniGridand Mario frames it was trained on plus a few held-out games, three episodes each. English only; calibration is measured on thelisted datasets, not on your images.
## Changelog
| version | what changed ||---|---|| **current weights** | v5 text weights transplanted into the Qwen3.5-2B vision-language model, one epoch on game frames, The Cauldron multiple-choice tasks and a text replay, then PPO from pixels on Breakout and Pong || previous release | v4-based: Breakout 16, Pong 8, Freeway 8, BabyAI-GoTo 0.30 |
Every decider release is listed in [docs/CHANGELOG.md](https://github.com/Mapika/decider/blob/main/docs/CHANGELOG.md) of theGitHub repository.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154{%- set image_count = namespace(value=0) %}{%- set video_count = namespace(value=0) %}{%- macro render_content(content, do_vision_count, is_system_content=false) %} {%- if content is string %} {{- content }} {%- elif content is iterable and content is not mapping %} {%- for item in content %} {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} {%- if is_system_content %} {{- raise_exception('System message cannot contain images.') }} {%- endif %} {%- if do_vision_count %} {%- set image_count.value = image_count.value + 1 %} {%- endif %} {%- if add_vision_id %} {{- 'Picture ' ~ image_count.value ~ ': ' }} {%- endif %} {{- '<|vision_start|><|image_pad|><|vision_end|>' }} {%- elif 'video' in item or item.type == 'video' %} {%- if is_system_content %} {{- raise_exception('System message cannot contain videos.') }} {%- endif %} {%- if do_vision_count %} {%- set video_count.value = video_count.value + 1 %} {%- endif %} {%- if add_vision_id %} {{- 'Video ' ~ video_count.value ~ ': ' }} {%- endif %} {{- '<|vision_start|><|video_pad|><|vision_end|>' }} {%- elif 'text' in item %} {{- item.text }} {%- else %} {{- raise_exception('Unexpected item type in content.') }} {%- endif %} {%- endfor %} {%- elif content is none or content is undefined %} {{- '' }} {%- else %} {{- raise_exception('Unexpected content type.') }} {%- endif %}{%- endmacro %}{%- if not messages %} {{- raise_exception('No messages provided.') }}{%- endif %}{%- if tools and tools is iterable and tools is not mapping %} {{- '<|im_start|>system\n' }} {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }} {%- for tool in tools %} {{- "\n" }} {{- tool | tojson }} {%- endfor %} {{- "\n</tools>" }} {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }} {%- if messages[0].role == 'system' %} {%- set content = render_content(messages[0].content, false, true)|trim %} {%- if content %} {{- '\n\n' + content }} {%- endif %} {%- endif %} {{- '<|im_end|>\n' }}{%- else %} {%- if messages[0].role == 'system' %} {%- set content = render_content(messages[0].content, false, true)|trim %} {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} {%- endif %}{%- endif %}{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}{%- for message in messages[::-1] %} {%- set index = (messages|length - 1) - loop.index0 %} {%- if ns.multi_step_tool and message.role == "user" %} {%- set content = render_content(message.content, false)|trim %} {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %} {%- set ns.multi_step_tool = false %} {%- set ns.last_query_index = index %} {%- endif %} {%- endif %}{%- endfor %}{%- if ns.multi_step_tool %} {{- raise_exception('No user query found in messages.') }}{%- endif %}{%- for message in messages %} {%- set content = render_content(message.content, true)|trim %} {%- if message.role == "system" %} {%- if not loop.first %} {{- raise_exception('System message must be at the beginning.') }} {%- endif %} {%- elif message.role == "user" %} {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} {%- elif message.role == "assistant" %} {%- set reasoning_content = '' %} {%- if message.reasoning_content is string %} {%- set reasoning_content = message.reasoning_content %} {%- else %} {%- if '</think>' in content %} {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %} {%- set content = content.split('</think>')[-1].lstrip('\n') %} {%- endif %} {%- endif %} {%- set reasoning_content = reasoning_content|trim %} {%- if loop.index0 > ns.last_query_index %} {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }} {%- else %} {{- '<|im_start|>' + message.role + '\n' + content }} {%- endif %} {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} {%- for tool_call in message.tool_calls %} {%- if tool_call.function is defined %} {%- set tool_call = tool_call.function %} {%- endif %} {%- if loop.first %} {%- if content|trim %} {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- else %} {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- endif %} {%- else %} {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- endif %} {%- if tool_call.arguments is defined %} {%- for args_name, args_value in tool_call.arguments|items %} {{- '<parameter=' + args_name + '>\n' }} {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} {{- args_value }} {{- '\n</parameter>\n' }} {%- endfor %} {%- endif %} {{- '</function>\n</tool_call>' }} {%- endfor %} {%- endif %} {{- '<|im_end|>\n' }} {%- elif message.role == "tool" %} {%- if loop.previtem and loop.previtem.role != "tool" %} {{- '<|im_start|>user' }} {%- endif %} {{- '\n<tool_response>\n' }} {{- content }} {{- '\n</tool_response>' }} {%- if not loop.last and loop.nextitem.role != "tool" %} {{- '<|im_end|>\n' }} {%- elif loop.last %} {{- '<|im_end|>\n' }} {%- endif %} {%- else %} {{- raise_exception('Unexpected message role.') }} {%- endif %}{%- endfor %}{%- if add_generation_prompt %} {{- '<|im_start|>assistant\n' }} {%- if enable_thinking is defined and enable_thinking is true %} {{- '<think>\n' }} {%- else %} {{- '<think>\n\n</think>\n\n' }} {%- endif %}{%- endif %}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105{ "architectures": [ "Qwen3_5ForConditionalGeneration" ], "dtype": "bfloat16", "image_token_id": 248056, "model_type": "qwen3_5", "text_config": { "attention_bias": false, "attention_dropout": 0.0, "attn_output_gate": true, "bos_token_id": null, "dtype": "bfloat16", "eos_token_id": 248044, "full_attention_interval": 4, "head_dim": 256, "hidden_act": "silu", "hidden_size": 2048, "initializer_range": 0.02, "intermediate_size": 6144, "layer_types": [ "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention" ], "linear_conv_kernel_dim": 4, "linear_key_head_dim": 128, "linear_num_key_heads": 16, "linear_num_value_heads": 16, "linear_value_head_dim": 128, "mamba_ssm_dtype": "float32", "max_position_embeddings": 262144, "mlp_only_layers": [], "model_type": "qwen3_5_text", "mtp_num_hidden_layers": 1, "mtp_use_dedicated_embeddings": false, "num_attention_heads": 8, "num_hidden_layers": 24, "num_key_value_heads": 2, "pad_token_id": null, "partial_rotary_factor": 0.25, "rms_norm_eps": 1e-06, "rope_parameters": { "mrope_interleaved": true, "mrope_section": [ 11, 11, 10 ], "partial_rotary_factor": 0.25, "rope_theta": 10000000, "rope_type": "default" }, "tie_word_embeddings": true, "use_cache": true, "vocab_size": 248320 }, "tie_word_embeddings": true, "transformers_version": "5.17.0", "video_token_id": 248057, "vision_config": { "deepstack_visual_indexes": [], "depth": 24, "dtype": "bfloat16", "hidden_act": "gelu_pytorch_tanh", "hidden_size": 1024, "in_channels": 3, "initializer_range": 0.02, "intermediate_size": 4096, "model_type": "qwen3_5_vision", "num_heads": 16, "num_position_embeddings": 2304, "out_hidden_size": 2048, "patch_size": 16, "rope_parameters": { "rope_theta": 10000.0, "rope_type": "axial" }, "spatial_merge_size": 2, "temporal_patch_size": 2 }, "vision_end_token_id": 248054, "vision_start_token_id": 248053}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166"""Low-latency inference engine: shape-bucketed CUDA graphs over the one-pass decision model.
Right padding + causal layers => pad positions never influence earlier slots, so no attentionmask is needed and every (B, T) bucket can be captured once and replayed. The graph outputsoption-letter logits for all positions [B, T, K]; slots are gathered outside."""import time, torch, torch._dynamo, torch.nn.functional as Ffrom .model import DecisionModel, collatefrom .prompt import build, MAX_OPTIONS
T_BUCKETS = [64, 128, 192, 256, 320, 384, 512, 640, 768, 1024, 1280, 1536, 2048]B_BUCKETS = [1, 2, 4, 8, 16, 32, 64]
def _bucket(x, buckets): for b in buckets: if x <= b: return b return None
def fused_causal_conv1d_fn(hidden_states, weight, bias=None, activation=None, **kwargs): """Depthwise causal conv (kernel k) as k shifted multiply-adds: fuses under torch.compile, unlike the cuDNN grouped conv fallback (which was ~11% of batched GPU time).""" B, C, T = hidden_states.shape; k = weight.shape[-1] x = F.pad(hidden_states.to(weight.dtype), (k - 1, 0)) out = x[:, :, k - 1:k - 1 + T] * weight[:, k - 1][None, :, None] for j in range(k - 1): out = out + x[:, :, j:j + T] * weight[:, j][None, :, None] if bias is not None: out = out + bias[None, :, None] if activation == "silu": out = F.silu(out) elif activation is not None: from transformers.activations import ACT2FN out = ACT2FN[activation](out) return out.to(hidden_states.dtype)
def patch_conv(): from transformers.models.qwen3_5 import modeling_qwen3_5 as mq mq.causal_conv1d_fn = fused_causal_conv1d_fn
class Engine: """compile: torch.compile the forward (needs use_cache=False; ~1.4x batched, fuses elementwise work). fp8: e4m3 weights + per-token activation scaling on the big linears (Hopper tensor cores). conv_patch: fusable depthwise causal conv instead of the cuDNN fallback.""" def __init__(self, path, device="cuda", dtype=torch.bfloat16, use_graphs=True, max_ctx_tokens=1536, compile=True, fp8=False, conv_patch=True): if conv_patch: patch_conv() self.m = DecisionModel(path, dtype=dtype, grad_ckpt=False).to(device).eval() self.tok = self.m.tok; self.dev = device; self.use_graphs = use_graphs; self.max_ctx = max_ctx_tokens self.core, self.W = self.m.lm.model, self.m.lm.lm_head.weight[self.m.letters].detach().clone() self.cfg = dict(compile=compile, fp8=fp8, conv_patch=conv_patch, graphs=use_graphs) if fp8: from .fp8 import convert_to_fp8 self.cfg["fp8_layers"] = convert_to_fp8(self.core) if compile: torch._dynamo.config.cache_size_limit = 128 self._fwd_impl = torch.compile(self._fwd_eager, dynamic=False) else: self._fwd_impl = self._fwd_eager self.graphs = {} # (B, T) -> (static_ids, static_out, graph) self.pool = torch.cuda.graph_pool_handle() if use_graphs else None self.stats = dict(graph_captures=0, forwards=0)
def _fwd_eager(self, ids): h = self.core(input_ids=ids, use_cache=False).last_hidden_state return F.linear(h, self.W).float() # [B, T, K]
@torch.no_grad() def _fwd(self, ids): return self._fwd_impl(ids)
def _capture(self, B, T): s_ids = torch.full((B, T), self.tok.pad_token_id, dtype=torch.long, device=self.dev) st = torch.cuda.Stream(); st.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(st): for _ in range(3): self._fwd(s_ids) # warm-up: compile / triton autotune torch.cuda.current_stream().wait_stream(st) g = torch.cuda.CUDAGraph() with torch.cuda.graph(g, pool=self.pool): s_out = self._fwd(s_ids) self.stats["graph_captures"] += 1 return s_ids, s_out, g
@torch.no_grad() def logits_all(self, ids): """ids: [B, T] long on device (already right-padded to a bucket). Returns [B, T, K] float.""" B, T = ids.shape; self.stats["forwards"] += 1 if not self.use_graphs: return self._fwd(ids) key = (B, T) if key not in self.graphs: self.graphs[key] = self._capture(B, T) s_ids, s_out, g = self.graphs[key] s_ids.copy_(ids); g.replay() return s_out
@torch.no_grad() def score_items(self, items, temperature=1.0): """items: list of dicts from prompt.build. Returns list of [n_q, MAX_OPTIONS] prob tensors (cpu).""" Tmax = max(len(it["ids"]) for it in items) T = _bucket(Tmax, T_BUCKETS) or Tmax; B = _bucket(len(items), B_BUCKETS) or len(items) ids = torch.full((B, T), self.tok.pad_token_id, dtype=torch.long) for b, it in enumerate(items): ids[b, :len(it["ids"])] = torch.tensor(it["ids"]) out = self.logits_all(ids.to(self.dev, non_blocking=True)) res = [] ar = torch.arange(MAX_OPTIONS, device=self.dev) for b, it in enumerate(items): sl = torch.tensor(it["slots"], device=self.dev) lg = out[b, sl] # [n_q, K] nop = torch.tensor(it["nopts"], device=self.dev) lg = lg.masked_fill(ar[None, :] >= nop[:, None], float("-inf")) res.append(torch.softmax(lg / temperature, -1).cpu()) return res
def warmup(self, shapes=((1, 128), (1, 256), (1, 384), (1, 512), (8, 256), (8, 512), (32, 256), (32, 512))): t = time.time() for B, T in shapes: self.logits_all(torch.full((B, T), self.tok.pad_token_id, dtype=torch.long, device=self.dev)) torch.cuda.synchronize(); return time.time() - t
if __name__ == "__main__": import sys, random, numpy as np from . import data as D from .infer import Decider path = sys.argv[1] if len(sys.argv) > 1 else "runs/r3_v2/model" cfg = dict(compile="nocompile" not in sys.argv[2:], fp8="fp8" in sys.argv[2:], conv_patch="noconv" not in sys.argv[2:]) _, evals = D.load_cache("data/tasks.pkl") eng = Engine(path, **cfg); print("engine cfg", eng.cfg) rng = random.Random(0) exs = evals["support_tickets"][:64] + evals["clinc_oos"][:64] + evals["race"][:32] items = [build(e, eng.tok, rng, max_ctx_tokens=1536) for e in exs] # correctness vs eager masked forward (DecisionModel.slot_logits) ref = [] with torch.no_grad(): for i in range(0, len(items), 16): b = collate(items[i:i + 16], eng.tok.pad_token_id) lg = eng.m.slot_logits(b["input_ids"].cuda(), b["attention_mask"].cuda(), b["slot_idx"].cuda(), b["slot_batch"].cuda(), b["nopts"].cuda()) ref.append(torch.softmax(lg, -1).cpu()) ref = torch.cat(ref) got = torch.cat(eng.score_items(items)) print(f"max |p_graph - p_eager| = {(ref - got).abs().max():.4f} over {len(ref)} questions; argmax agreement {(ref.argmax(1) == got.argmax(1)).float().mean():.4f}") print(f"warmup capture of 8 buckets: {eng.warmup():.1f}s; captures so far {eng.stats['graph_captures']}") # latency: single real requests for name, pool in [("support_tickets", exs[:64]), ("clinc_oos", exs[64:128]), ("race", exs[128:])]: its = [build(e, eng.tok, rng) for e in pool] ts = [] for it in its[:40]: torch.cuda.synchronize(); t = time.time(); eng.score_items([it]); torch.cuda.synchronize(); ts.append(time.time() - t) ts = np.array(ts[5:]) * 1000 print(f"single request {name:16s}: p50 {np.median(ts):5.1f} ms p90 {np.percentile(ts, 90):5.1f} ms (avg {np.mean([len(i['ids']) for i in its]):.0f} tok, {len(its[0]['slots'])} q)") for bs in (8, 32): ts = [] for i in range(0, min(len(its), bs * 6), bs): chunk = its[i:i + bs] if len(chunk) < bs: break torch.cuda.synchronize(); t = time.time(); eng.score_items(chunk); torch.cuda.synchronize(); ts.append(time.time() - t) ts = np.array(ts[1:]) * 1000 print(f" batch {bs:2d}: p50 {np.median(ts):6.1f} ms -> {bs/np.median(ts)*1000:6.0f} ctx/s, {bs*len(its[0]['slots'])/np.median(ts)*1000:6.0f} decisions/s") print("stats", eng.stats, "graphs", len(eng.graphs), f"mem {torch.cuda.memory_reserved()/1e9:.1f} GB")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354"""FP8 (e4m3) linear layers for Hopper via torch._scaled_mm.Weights: per-output-channel scales, quantised once. Activations: per-token dynamic scales.Under torch.compile the quantisation ops fuse into the surrounding elementwise work."""import torch, torch.nn as nn
E4M3_MAX = 448.0
def _quant_rowwise(x): s = x.abs().amax(dim=-1, keepdim=True).float().clamp(min=1e-12) / E4M3_MAX return (x.float() / s).clamp(-E4M3_MAX, E4M3_MAX).to(torch.float8_e4m3fn), s
class FP8Linear(nn.Module): def __init__(self, lin: nn.Linear): super().__init__() wq, sw = _quant_rowwise(lin.weight.detach()) # [N,K] fp8, [N,1] self.register_buffer("wq", wq.contiguous()) # [N,K]; passed as wq.t() -> [K,N] column-major, as _scaled_mm wants self.register_buffer("sw_t", sw.t().contiguous()) # [1,N] self.bias = None if lin.bias is None else nn.Parameter(lin.bias.detach().clone(), requires_grad=False) self.in_features, self.out_features = lin.in_features, lin.out_features self.out_dtype = lin.weight.dtype
def forward(self, x): shp = x.shape[:-1] x2 = x.reshape(-1, self.in_features) xq, sx = _quant_rowwise(x2) y = torch._scaled_mm(xq, self.wq.t(), scale_a=sx, scale_b=self.sw_t, bias=self.bias, out_dtype=self.out_dtype) return y.reshape(*shp, self.out_features)
def convert_to_fp8(model, skip=("lm_head",), min_dim=1024): """Replace nn.Linear (with in/out >= min_dim) by FP8Linear in place. Returns count.""" n = 0 for name, mod in list(model.named_modules()): for cname, child in list(mod.named_children()): full = f"{name}.{cname}" if name else cname if isinstance(child, nn.Linear) and not any(s in full for s in skip) and min(child.in_features, child.out_features) >= min_dim: setattr(mod, cname, FP8Linear(child)); n += 1 return n
if __name__ == "__main__": import time lin = nn.Linear(2048, 6144, bias=False).cuda().to(torch.bfloat16) f8 = FP8Linear(lin) x = torch.randn(8192, 2048, device="cuda", dtype=torch.bfloat16) ref = lin(x); got = f8(x) print("rel err", ((ref.float() - got.float()).abs().mean() / ref.float().abs().mean()).item()) for f, name in [(lin, "bf16 linear"), (f8, "fp8 linear (eager)"), (torch.compile(f8), "fp8 linear (compiled)")]: for _ in range(3): f(x) torch.cuda.synchronize(); t = time.time() for _ in range(20): f(x) torch.cuda.synchronize(); print(f"{name:24s} {(time.time()-t)/20*1000:.3f} ms")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187"""Usable inference API: typed decisions with probabilities, all from one forward pass.
from decider.infer import Decider d = Decider("runs/r2_full/model") out = d.decide("My card was charged twice for the same purchase.", [{"question": "Which department should handle this?", "options": ["billing", "technical", "sales"]}, {"question": "How urgent is this?", "options": ["low", "medium", "high"]}]) # -> [{'choice': 'billing', 'confidence': 0.97, 'probs': {...}}, {...}]"""import torchfrom .model import DecisionModel, collatefrom .prompt import build, MAX_OPTIONSfrom dataclasses import dataclass
@dataclassclass Q: text: str; options: list; gold: int = 0
@dataclassclass Example: context: str; qs: list; task: str = "infer"; image: bytes = None
NEUTRAL_NONE = "not listed here"
def neutralize_options(options): """The training augmentation used the literal 'none of the above', and the model learned that exact string as an abstain signal (it abstains even on clear cases when the string is offered). Any option that reads like it is rewritten to a neutral phrasing for the model and mapped back in the output.""" out, back = [], {} for o in options: key = o.strip().lower() if key.startswith("none of the above") or key in ("none of the above", "none", "n/a", "none of these"): out.append(NEUTRAL_NONE); back[NEUTRAL_NONE] = o else: out.append(o) return out, back
class Decider: """use_graphs=True (default on CUDA) routes scoring through decider.engine.Engine: shape-bucketed CUDA graphs, ~7x lower single-request latency than eager. Set False for CPU or debugging.""" def __init__(self, path, device="cuda", dtype=torch.bfloat16, temperature=None, abstain_below=0.0, use_graphs=None): import json, os cfg = {} try: # model folder may carry decider_config.json (temperature, flags) from huggingface_hub import hf_hub_download cfg_path = os.path.join(path, "decider_config.json") if os.path.isdir(path) else hf_hub_download(path, "decider_config.json") cfg = json.load(open(cfg_path)) except Exception: pass if temperature is None: temperature = float(cfg.get("temperature", 1.0)) self.neutralize_none = bool(cfg.get("neutralize_none", True)) # v4 and earlier learned the literal string as an abstain signal if use_graphs is None: use_graphs = str(device).startswith("cuda") if use_graphs: from .engine import Engine self.eng = Engine(path, device=device, dtype=dtype); self.m = self.eng.m else: self.eng = None; self.m = DecisionModel(path, dtype=dtype, grad_ckpt=False).to(device).eval() self.dev = device; self.T = temperature; self.abstain_below = abstain_below
@torch.no_grad() def decide_batch(self, requests, max_ctx_tokens=1536): """requests: list of (context:str, questions:list[dict(question, options)]). One forward pass for everything.""" exs, meta = [], [] if self.neutralize_none: requests = [(context, [dict(q, options=neutralize_options(q["options"])[0], _back=neutralize_options(q["options"])[1]) for q in qs]) for context, qs in requests] for context, qs in requests: for q in qs: assert 2 <= len(q["options"]) <= MAX_OPTIONS, f"2..{MAX_OPTIONS} options required" exs.append(Example(context, [Q(q["question"], list(q["options"]), 0) for q in qs], "infer")) class _NoShuffle: # keep option order as given def shuffle(self, x): pass def sample(self, xs, k): return xs[:k] items = [build(e, self.m.tok, _NoShuffle(), max_ctx_tokens=max_ctx_tokens) for e in exs] if self.eng is not None: probs = torch.cat(self.eng.score_items(items, temperature=self.T)) else: b = collate(items, self.m.tok.pad_token_id) logits = self.m.slot_logits(b["input_ids"].to(self.dev), b["attention_mask"].to(self.dev), b["slot_idx"].to(self.dev), b["slot_batch"].to(self.dev), b["nopts"].to(self.dev)) probs = torch.softmax(logits / self.T, -1).cpu() out, k = [], 0 for context, qs in requests: res = [] for q in qs: p = probs[k, :len(q["options"])].tolist(); k += 1 j = max(range(len(p)), key=p.__getitem__); back = q.get("_back", {}) names = [back.get(o, o) for o in q["options"]] res.append(dict(choice=names[j] if p[j] >= self.abstain_below else None, confidence=p[j], probs={o: pi for o, pi in zip(names, p)})) out.append(res) return out
def decide(self, context, questions, **kw): return self.decide_batch([(context, questions)], **kw)[0]
# ---- typed schema interface: {question: {"type": "bool"} | {"type": "choice", "options": [...]} # | {"type": "scale", "legend": {"0": "none", "1": "low", ...}}} @staticmethod def _schema_to_questions(schema): qs = [] for qtext, spec in schema.items(): t = spec.get("type", "choice") if t == "bool": qs.append(dict(question=qtext, options=["no", "yes"])) elif t == "choice": qs.append(dict(question=qtext, options=list(spec["options"]))) elif t == "scale": leg = spec["legend"] keys = sorted(leg, key=lambda k: float(k)) if isinstance(leg, dict) else list(range(len(leg))) labels = [f"{k}: {leg[k]}" if isinstance(leg, dict) else f"{i}: {leg[i]}" for i, k in enumerate(keys)] qs.append(dict(question=qtext, options=labels, _keys=keys, _legend=leg)) else: raise ValueError(f"unknown field type {t}") return qs
def decide_json_batch(self, requests, **kw): """requests: list of (context, schema). Returns one dict per context keyed by question.""" qss = [self._schema_to_questions(schema) for _, schema in requests] raw = self.decide_batch([(ctx, qs) for (ctx, _), qs in zip(requests, qss)], **kw) out = [] for (ctx, schema), qs, res in zip(requests, qss, raw): o = {} for (qtext, spec), q, r in zip(schema.items(), qs, res): t = spec.get("type", "choice") if t == "bool": o[qtext] = {"noul": round(r["probs"]["yes"], 4), "type": "noul"} elif t == "choice": o[qtext] = {"choice": r["choice"], "confidence": round(r["confidence"], 4), "type": "choice", "probabilities": {k: round(v, 4) for k, v in r["probs"].items()}} else: p = [r["probs"][lab] for lab in q["options"]] keys = q["_keys"]; n = len(p) score = sum(float(k) * pi for k, pi in zip(keys, p)) # expected level on the legend scale j = max(range(n), key=p.__getitem__) o[qtext] = {"score": round(score, 2), "confidence": round(p[j], 4), "type": "scale", "legend": q["_legend"], "probabilities": {str(keys[i]): round(pi, 4) for i, pi in enumerate(p)}} out.append(o) return out
def decide_json(self, context, schema, **kw): return self.decide_json_batch([(context, schema)], **kw)[0]
if __name__ == "__main__": import sys, json, time d = Decider(sys.argv[1] if len(sys.argv) > 1 else "runs/r1_200k/model") demo = [ ("My card was charged twice for the same purchase and I want the extra charge refunded.", [{"question": "Which department should handle this?", "options": ["billing", "technical support", "sales"]}, {"question": "What is the customer's sentiment?", "options": ["angry", "neutral", "happy"]}, {"question": "Does this need a refund action?", "options": ["no", "yes"]}]), ("hey can u turn the lights off in the kitchen", [{"question": "What is the intent?", "options": ["smart home control", "set alarm", "play music", "none of the above"]}, {"question": "Is this request toxic?", "options": ["no", "yes"]}]), ("The quarterly report shows revenue fell 12% while costs rose sharply.", [{"question": "What is the financial sentiment?", "options": ["bearish", "neutral", "bullish"]}]), ] t = time.time(); res = d.decide_batch(demo); dt = time.time() - t for (ctx, qs), r in zip(demo, res): print("\n>>", ctx) for q, a in zip(qs, r): print(f" {q['question']:45s} -> {a['choice']!s:22s} p={a['confidence']:.2f} " + " ".join(f"{o}:{p:.2f}" for o, p in a['probs'].items())) print(f"\n{sum(len(q) for _, q in demo)} decisions in {dt*1000:.0f} ms (one forward pass)") schema = { "Revenue currently impacted?": {"type": "bool"}, "What business impact?": {"type": "choice", "options": ["none", "degraded", "outage"]}, "Integration issue present?": {"type": "bool"}, "Account health status?": {"type": "choice", "options": ["healthy", "watch", "at risk"]}, "Which incident scope?": {"type": "choice", "options": ["single_account", "multi_account", "platform_wide"]}, "Security concern present?": {"type": "bool"}, "Duplicate charge reported?": {"type": "bool"}, "Churn likelihood level?": {"type": "scale", "legend": {"0": "none", "1": "low", "2": "medium", "3": "high"}}, "Human attention needed?": {"type": "bool"}, "Immediate feature request?": {"type": "bool"}, } ctx = ("Hi, since this morning our Stripe webhook integration stopped firing and our checkout is down for all customers. " "We are losing orders every minute and our partner launch is on Thursday. Also I think we got billed twice last week. " "If this is not fixed today we will have to look at other providers.") t = time.time(); js = d.decide_json(ctx, schema); dt = time.time() - t print(f"\n>> {ctx[:80]}...\n" + json.dumps(js, indent=1)[:3000]); print(f"{len(schema)} typed fields in {dt*1000:.0f} ms (one forward pass)")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647"""Backbone -> slot hidden states -> restricted logits over option letters."""import torch, torch.nn as nn, torch.nn.functional as Ffrom transformers import AutoModelForCausalLM, AutoTokenizerfrom .prompt import letter_ids, MAX_OPTIONS
class DecisionModel(nn.Module): def __init__(self, name, dtype=torch.bfloat16, grad_ckpt=True): super().__init__() self.tok = AutoTokenizer.from_pretrained(name) self.lm = AutoModelForCausalLM.from_pretrained(name, dtype=dtype) if grad_ckpt: self.lm.gradient_checkpointing_enable() self.register_buffer("letters", torch.tensor(letter_ids(self.tok)), persistent=False)
def slot_logits(self, input_ids, attention_mask, slot_idx, slot_batch, nopts): """input_ids [B,T]; slot_idx/slot_batch [N] flat slot positions; nopts [N]. Returns [N, MAX_OPTIONS] logits with invalid options masked to -inf.""" h = self.lm.model(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state hs = h[slot_batch, slot_idx] # [N,H] W = self.lm.lm_head.weight[self.letters] # [K,H] logits = F.linear(hs, W).float() # [N,K] ar = torch.arange(MAX_OPTIONS, device=logits.device)[None, :] logits = logits.masked_fill(ar >= nopts[:, None], float("-inf")) return logits
def forward(self, batch): return self.slot_logits(batch["input_ids"], batch["attention_mask"], batch["slot_idx"], batch["slot_batch"], batch["nopts"])
def collate(items, pad_id): """items: list of dicts from prompt.build (+ 'task', 'ex_id'). Right-pad.""" T = max(len(it["ids"]) for it in items) T = ((T + 63) // 64) * 64 # few distinct shapes -> fewer kernel (re)compiles B = len(items) input_ids = torch.full((B, T), pad_id, dtype=torch.long) attn = torch.zeros((B, T), dtype=torch.long) slot_idx, slot_batch, golds, nopts, tasks, qidx = [], [], [], [], [], [] for b, it in enumerate(items): n = len(it["ids"]) input_ids[b, :n] = torch.tensor(it["ids"]) attn[b, :n] = 1 for k, s in enumerate(it["slots"]): slot_idx.append(s); slot_batch.append(b); golds.append(it["golds"][k]); nopts.append(it["nopts"][k]) tasks.append(it.get("task", "")); qidx.append(k) return dict(input_ids=input_ids, attention_mask=attn, slot_idx=torch.tensor(slot_idx), slot_batch=torch.tensor(slot_batch), golds=torch.tensor(golds), nopts=torch.tensor(nopts), tasks=tasks, qidx=qidx)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061"""Prompt construction. One context, N typed questions, N answer slots.
All N decisions are read from a single forward pass: the logits at each"Answer k: (" slot are restricted to the option-letter tokens. No answerletters are ever inserted, so slot k sees the context and all questions butno earlier answers (the decisions are conditionally independent given input)."""import random
LETTERS = "ABCDEFGHIJ"MAX_OPTIONS = len(LETTERS)ABSTAIN_PREFIXES = ("none of the above", "none of these", "not listed", "no suitable", "does not apply", "cannot tell")ABSTAIN_EXACT = ("other", "unsure", "something else", "neither of these", "other / not covered")
def is_abstain_option(o): o = o.strip().lower() return o.startswith(ABSTAIN_PREFIXES) or o in ABSTAIN_EXACT
def build(example, tok, rng=None, max_options=MAX_OPTIONS, max_ctx_tokens=1536): """Returns dict(ids=list[int], slots=list[int], golds=list[int], nopts=list[int], perms=list[list[int]]).""" rng = rng or random ctx_ids = tok.encode("Context:\n" + example.context, add_special_tokens=False)[:max_ctx_tokens] ids = list(ctx_ids) slots, golds, nopts, perms = [], [], [], [] multi = len(example.qs) > 1 for k, q in enumerate(example.qs): opts = list(range(len(q.options))) if len(opts) > max_options: # always keep the gold and any abstain-style option (its mere presence must not carry information) forced = {q.gold} | {i for i, o in enumerate(q.options) if is_abstain_option(o)} others = [i for i in opts if i not in forced] keep = rng.sample(others, max_options - len(forced)) + list(forced) opts = keep rng.shuffle(opts) lines = [f"\n\nQuestion{' ' + str(k + 1) if multi else ''}: {q.text}\nOptions:"] for j, oi in enumerate(opts): lines.append(f"\n({LETTERS[j]}) {q.options[oi]}") lines.append(f"\nAnswer{' ' + str(k + 1) if multi else ''}: (") piece = tok.encode("".join(lines), add_special_tokens=False) ids.extend(piece) slots.append(len(ids) - 1) # position of " (" token golds.append(opts.index(q.gold) if q.gold in opts else -1) nopts.append(len(opts)) perms.append(opts) return dict(ids=ids, slots=slots, golds=golds, nopts=nopts, perms=perms)
def letter_ids(tok): out = [] for L in LETTERS: t = tok.encode(L, add_special_tokens=False) assert len(t) == 1, (L, t) out.append(t[0]) return out
def render(example, tok, **kw): b = build(example, tok, **kw) return tok.decode(b["ids"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""Vision variant: image(s) + the same lettered prompt, letter logits at the answer slots, one forward pass."""import io, torch, torch.nn as nn, torch.nn.functional as Ffrom PIL import Imagefrom transformers import AutoProcessor, AutoModelForImageTextToTextfrom .prompt import build, letter_ids, MAX_OPTIONS
IMG = "<|vision_start|><|image_pad|><|vision_end|>"
def to_pil(x): if isinstance(x, Image.Image): return x.convert("RGB") if isinstance(x, (bytes, bytearray)): return Image.open(io.BytesIO(x)).convert("RGB") return Image.fromarray(x).convert("RGB")
class VisionDecisionModel(nn.Module): def __init__(self, name, dtype=torch.bfloat16, grad_ckpt=True): super().__init__() self.proc = AutoProcessor.from_pretrained(name); self.tok = self.proc.tokenizer self.lm = AutoModelForImageTextToText.from_pretrained(name, dtype=dtype) if grad_ckpt: self.lm.gradient_checkpointing_enable() self.register_buffer("letters", torch.tensor(letter_ids(self.tok)), persistent=False) self.slot_tok = self.tok.encode(" (", add_special_tokens=False)[-1]; self.colon = self.tok.encode(":", add_special_tokens=False)[-1] self.answer_tok = self.tok.encode("Answer", add_special_tokens=False)[0]
def prepare(self, examples, max_ctx_tokens=1536): """examples: list of (image or None, Example). Returns processor inputs + slot bookkeeping.""" texts, images, golds, nopts, nq = [], [], [], [], [] for img, ex in examples: b = build(ex, self.tok, _NoShuffle(), max_ctx_tokens=max_ctx_tokens) txt = self.tok.decode(b["ids"]) texts.append((IMG if img is not None else "") + txt); golds.extend(b["golds"]); nopts.extend(b["nopts"]); nq.append(len(b["slots"])) if img is not None: images.append(to_pil(img)) self.tok.padding_side = "right" inp = self.proc(images=images or None, text=texts, return_tensors="pt", padding=True) ids = inp["input_ids"] slot_idx, slot_batch = [], [] for bi in range(ids.shape[0]): row = ids[bi].tolist(); found = [] for i in range(2, len(row)): if row[i] == self.slot_tok and row[i - 1] == self.colon and self.answer_tok in row[max(0, i - 5):i]: found.append(i) assert len(found) == nq[bi], (len(found), nq[bi], self.tok.decode(row[-40:])) slot_idx.extend(found); slot_batch.extend([bi] * len(found)) inp["slot_idx"] = torch.tensor(slot_idx); inp["slot_batch"] = torch.tensor(slot_batch) inp["golds"] = torch.tensor(golds); inp["nopts"] = torch.tensor(nopts) return inp
def slot_logits(self, inp): dev = self.letters.device kw = {k: v.to(dev) for k, v in inp.items() if k in ("input_ids", "attention_mask", "pixel_values", "image_grid_thw", "mm_token_type_ids")} h = self.lm.model(**kw, use_cache=False).last_hidden_state # [B, T, H] hs = h[inp["slot_batch"].to(dev), inp["slot_idx"].to(dev)] # [N, H] lg = F.linear(hs, self.lm.lm_head.weight[self.letters]).float() # [N, K] letter logits only ar = torch.arange(MAX_OPTIONS, device=dev)[None, :] return lg.masked_fill(ar >= inp["nopts"].to(dev)[:, None], float("-inf"))
class _NoShuffle: def shuffle(self, x): pass def sample(self, xs, k): return xs[:k]
if __name__ == "__main__": import time, numpy as np from .infer import Example, Q import gym_super_mario_bros from nes_py.wrappers import JoypadSpace from gym_super_mario_bros.actions import SIMPLE_MOVEMENT m = VisionDecisionModel("Qwen/Qwen3.5-2B-Base", grad_ckpt=False).cuda().eval() env = JoypadSpace(gym_super_mario_bros.make("SuperMarioBros-1-1-v0"), SIMPLE_MOVEMENT); obs = env.reset() for _ in range(100): obs, _, _, _ = env.step(3) ex = Example("The image shows the current Super Mario Bros screen. Mario runs right; jump over enemies and gaps.", [Q("What should Mario do right now?", ["run right", "jump right", "step left", "wait"], 0), Q("Is an enemy visible?", ["no", "yes"], 1)]) inp = m.prepare([(obs, ex), (None, ex)]) with torch.no_grad(): lg = m.slot_logits(inp) print("slots found:", inp["slot_idx"].tolist(), "batch", inp["slot_batch"].tolist(), "tokens", inp["input_ids"].shape) print("probs (image / no image):", [[round(x, 3) for x in torch.softmax(r, -1)[:4].tolist()] for r in lg])1{"neutralize_none": false, "version": "v5-vision", "base": "Qwen/Qwen3.5-2B-Base"}123456{ "_from_model_config": true, "eos_token_id": 248044, "transformers_version": "5.17.0", "use_cache": true}123version https://git-lfs.github.com/spec/v1oid sha256:ac99c16652524d0c6a8017c987efb8aeaca5050f0bf3c7a3d92b927a57ec17ecsize 442655886412345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061{ "image_processor": { "do_convert_rgb": true, "do_normalize": true, "do_rescale": true, "do_resize": true, "image_mean": [ 0.5, 0.5, 0.5 ], "image_processor_type": "Qwen2VLImageProcessor", "image_std": [ 0.5, 0.5, 0.5 ], "merge_size": 2, "patch_size": 16, "resample": 3, "rescale_factor": 0.00392156862745098, "size": { "longest_edge": 16777216, "shortest_edge": 65536 }, "temporal_patch_size": 2 }, "processor_class": "Qwen3VLProcessor", "video_processor": { "do_convert_rgb": true, "do_normalize": true, "do_rescale": true, "do_resize": true, "do_sample_frames": true, "fps": 2, "image_mean": [ 0.5, 0.5, 0.5 ], "image_std": [ 0.5, 0.5, 0.5 ], "max_frames": 768, "max_video_tokens": 768, "merge_size": 2, "min_frames": 4, "patch_size": 16, "resample": 3, "rescale_factor": 0.00392156862745098, "return_metadata": false, "size": { "longest_edge": 234881024, "shortest_edge": 4096 }, "temporal_patch_size": 2, "video_processor_type": "Qwen3VLVideoProcessor" }}123version https://git-lfs.github.com/spec/v1oid sha256:b6d27c11283798debbfbcb1bd3bbdbcebac6c9b20d0be0c5b79231c97de97501size 1998949312345678910111213141516171819202122232425262728293031323334353637{ "add_prefix_space": false, "audio_bos_token": "<|audio_start|>", "audio_eos_token": "<|audio_end|>", "audio_token": "<|audio_pad|>", "backend": "tokenizers", "bos_token": null, "clean_up_tokenization_spaces": false, "eos_token": "<|endoftext|>", "errors": "replace", "image_token": "<|image_pad|>", "is_local": true, "local_files_only": false, "max_length": null, "model_max_length": 262144, "model_specific_special_tokens": { "audio_bos_token": "<|audio_start|>", "audio_eos_token": "<|audio_end|>", "audio_token": "<|audio_pad|>", "image_token": "<|image_pad|>", "video_token": "<|video_pad|>", "vision_bos_token": "<|vision_start|>", "vision_eos_token": "<|vision_end|>" }, "pad_to_multiple_of": null, "pad_token": "<|endoftext|>", "pad_token_type_id": 0, "padding_side": "right", "pretokenize_regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", "processor_class": "Qwen3VLProcessor", "split_special_tokens": false, "tokenizer_class": "Qwen2Tokenizer", "unk_token": null, "video_token": "<|video_pad|>", "vision_bos_token": "<|vision_start|>", "vision_eos_token": "<|vision_end|>"}.gitattributesAdded+36
README.mdAdded+92
chat_template.jinjaAdded+154
config.jsonAdded+105
decider/__init__.pyAdded
decider/engine.pyAdded+166
decider/fp8.pyAdded+54
decider/infer.pyAdded+187
decider/model.pyAdded+47
decider/prompt.pyAdded+61
decider/vision.pyAdded+78
decider_config.jsonAdded+1
generation_config.jsonAdded+6
model.safetensorsAdded+3
processor_config.jsonAdded+61
tokenizer.jsonAdded+3
tokenizer_config.jsonAdded+37