"""Kit engine on vLLM: a merged checkpoint (decision.merge), the same prompt ids and readout as decision.engine.LogitsEngine, prefill only. python -m decision_index run --engine decision.engine_vllm:VllmEngine \ --option model=/ldm/merged/v2f-a-0.75 --option temperature=1.0 --rows sample.jsonl --out runs/agree/vllm Pinned stack: vLLM 0.33.0 (torch 2.14.0, transformers >= 5.16.1, < 5.21) in its own venv; the training venv's transformers 5.22 is outside vLLM's pin. Gemma4ForConditionalGeneration has been in vLLM since 0.19.0 (2026-04-03); 0.33.0 carries the Gemma 4 fixes through October, and the board's Turion Jev 31B ran 0.32.0. vLLM's fix for unmerged LoRA on k_eq_v layers (PR #61267, 2026-11-02) is not in 0.33.0: another reason to serve merged weights. Readout. Each question's prompt goes to vLLM as token ids with SamplingParams(max_tokens=1, temperature=0, allowed_token_ids=, logprobs=), and the LLM runs with logprobs_mode="processed_logits". In vLLM's sampler (V1 runner: vllm/v1/sample/sampler.py; Model Runner V2, the default in 0.33: vllm/v1/worker/gpu/sample/sampler.py + logit_bias.py) the logits are the model's compute_logits output (Gemma 4: LM head, then the final softcap 30·tanh(x/30), as in HF) cast to float32; allowed_token_ids sets every other token to -inf; a greedy request gets no temperature, min-p, top-k/top-p or penalties; "processed_logits" returns exactly these masked logits, so the top-n entries are the n option codes with their raw softcapped logits. The engine divides them by its temperature and softmaxes, as decision.readout.log_probs does (with "processed_logprobs" the values are log-softmaxed over the codes first, which gives the same probabilities). The "raw_*" modes would be wrong here: their top-n is taken over the whole vocabulary before the allowed-token mask, so codes can be missing. Nothing is sampled from: the one generated token is discarded. Layout. As LogitsEngine: the merged checkpoint's merge.json carries the adapter's decision_config.json, whose "layout" ("v1" when missing) the engine renders with; `layout=` overrides it. `order_average=k` (default 1) reads each question in k option orders and averages, as LogitsEngine. Serving. All questions of a request go to vLLM in one llm.generate call (their prefills are batched and chunked; nothing is padded). With prefix caching on, when the request's prompts share at least `share_min_tokens` leading tokens, the first prompt is prefilled alone so the others reuse its cached prefix. The v1 question-first layout shares only the template and instruction; the v5 layout shares the whole block (instruction, every question of the request, the state, read twice when short), so every prompt after the first prefills only its own question, options and "Answer:" (plus the partial last KV block of the prefix). Cached and recomputed prefix KV come from the same weights and tokens, so the probabilities match the HF path (LogitsEngine) as closely as an unshared prefill does (tests/test_serving.py). Gemma 4 runs text only (`language_model_only`: the vision and audio towers are not built). Its 50 sliding-window layers (window 1,024, head_dim 256, 16 KV heads) and 10 full-attention layers (head_dim 512, 4 KV heads, K = V) have different head sizes (FlashAttention 2/3 stop at 256). vLLM's Gemma4Config (vllm/model_executor/models/config.py) then uses FlashAttention 4 for every layer when the build reports FA4 available (Hopper), else forces TRITON_ATTN. On an RTX PRO 6000 (sm_120) read the startup line "Gemma4 model has heterogeneous head dimensions ...": vLLM's FA4 path on Blackwell takes head_dim <= 256 only, so if FA4 is picked there and fails, pass --option attention_backend=TRITON_ATTN (the board's RTX PRO 6000 runs of SGLang and vLLM entrants list the Triton backend where FA3 is Hopper-only). Options: model (merged checkpoint or an untuned base), temperature, twice_max_tokens, layout, order_average, max_len (as LogitsEngine; prompts longer than max_len are refused, max_model_len = max_len + 1), gpu_memory_utilization (0.90), quantization (none; "fp8" = vLLM dynamic FP8 W8A8 at load, which puts the run under the board's 96 % quantized agreement bar), kv_cache_dtype ("auto"), enable_prefix_caching (true), max_num_batched_tokens (vLLM's default when unset), max_num_seqs, enforce_eager (false), attention_backend, share_min_tokens (512), logprobs_mode ("processed_logits"), language_model_only (true), llm_options (a JSON object of further vllm.LLM arguments). """ import json import math import pathlib from decision_index.engines import Engine, Unsupported from .prompt import (DEFAULT_LAYOUT, MAX_OPTIONS, TWICE_MAX_TOKENS, average_orders, check_layout, option_codes, option_orders, prompt_ids, request_prefix) LOGPROBS_MODES = ("processed_logits", "processed_logprobs") def _text(value): """As decision.engine._text (not imported: decision.engine needs peft, which the vLLM venv does not carry).""" if value is None: return "" return value if isinstance(value, str) else json.dumps(value, ensure_ascii=False) def _bool(value): return value if isinstance(value, bool) else str(value).strip().lower() in ("1", "true", "yes", "on") def code_probabilities(values, temperature=1.0): """softmax(values / T) in float64: values are the option codes' logits (or log-probs over the codes).""" scaled = [v / temperature for v in values] top = max(scaled) e = [math.exp(v - top) for v in scaled] total = sum(e) return [x / total for x in e] def read_codes(output, code_ids): """The option codes' values from one vLLM RequestOutput (max_tokens=1, logprobs=len(code_ids)).""" step = output.outputs[0].logprobs[0] missing = [t for t in code_ids if t not in step] if missing: raise RuntimeError(f"vLLM returned no logprob for option-code tokens {missing[:5]}: check logprobs_mode and " f"max_logprobs") values = [float(step[t].logprob) for t in code_ids] if not all(math.isfinite(v) for v in values): raise RuntimeError(f"non-finite option-code logits {values[:5]}") return values def common_prefix(prompts): first = prompts[0] n = len(first) for p in prompts[1:]: n = min(n, len(p)) for i in range(n): if p[i] != first[i]: n = i break return n class VllmEngine(Engine): name = "logits-sigma-1" latency = ("one llm.generate per request (vLLM, in-process): every question's prompt prefilled together, " "max_tokens=1 restricted to the option codes, prefix caching; prompt construction included") layout = DEFAULT_LAYOUT # set per engine in __init__; class defaults serve engines built without an LLM order_average = 1 def __init__(self, **options): super().__init__(**options) if options.get("adapter"): raise ValueError("VllmEngine serves merged weights: run `python -m decision.merge --model " "--adapter --scale <λ> --out ` and pass model=") if options.get("model_b"): raise ValueError("the two-backbone ensemble runs on decision.engine.LogitsEngine only") from transformers import AutoTokenizer from vllm import LLM, SamplingParams self._sampling = SamplingParams self.model_name = str(options["model"]) self.merge_record = self._merge_record(self.model_name) if self.merge_record.get("decision_config", {}).get("bidirectional"): raise ValueError(f"{self.model_name} was merged from a bidirectional adapter; vLLM serves causal " f"attention only, so it would not reproduce the trained readout") self.temperature = float(options.get("temperature", 1.0)) self.twice = int(options.get("twice_max_tokens", TWICE_MAX_TOKENS)) trained = self.merge_record.get("decision_config", {}) self.layout = check_layout(options.get("layout") or trained.get("layout") or DEFAULT_LAYOUT) self.order_average = int(options.get("order_average", 1)) self.max_len = int(options.get("max_len", 131072)) self.share_min_tokens = int(options.get("share_min_tokens", 512)) self.prefix_caching = _bool(options.get("enable_prefix_caching", True)) self.logprobs_mode = options.get("logprobs_mode", "processed_logits") if self.logprobs_mode not in LOGPROBS_MODES: raise ValueError(f"logprobs_mode must be one of {LOGPROBS_MODES}: the raw modes take the top-n over the " f"whole vocabulary before the allowed-token mask") self.device = "vllm" # bench_latency: llm.generate returns after the GPU work, nothing to synchronize here self.tok = AutoTokenizer.from_pretrained(options.get("tokenizer") or self.model_name) self.codes, self.code_ids = option_codes(self.tok) llm = { "model": self.model_name, "tokenizer": options.get("tokenizer") or self.model_name, "dtype": options.get("dtype", "bfloat16"), "max_model_len": self.max_len + 1, "gpu_memory_utilization": float(options.get("gpu_memory_utilization", 0.90)), "enable_prefix_caching": self.prefix_caching, "max_logprobs": MAX_OPTIONS, "logprobs_mode": self.logprobs_mode, "language_model_only": _bool(options.get("language_model_only", True)), "enforce_eager": _bool(options.get("enforce_eager", False)), "seed": int(options.get("seed", 0)), } for key, cast in (("quantization", str), ("kv_cache_dtype", str), ("attention_backend", str), ("max_num_batched_tokens", int), ("max_num_seqs", int)): if options.get(key) not in (None, "", "none"): llm[key] = cast(options[key]) extra = options.get("llm_options") or {} llm |= json.loads(extra) if isinstance(extra, str) else dict(extra) self.llm_options = llm self.llm = LLM(**llm) self._params = {} self.provenance = {"model": self.model_name, "merge": self.merge_record, "temperature": self.temperature, "twice_max_tokens": self.twice, "max_len": self.max_len, "serving": "vllm", "layout": self.layout, "order_average": self.order_average, "llm_options": {k: v for k, v in llm.items() if k not in ("model", "tokenizer")}} @staticmethod def _merge_record(model): path = pathlib.Path(model) / "merge.json" return json.loads(path.read_text()) if path.exists() else {} def _question(self, q): """As LogitsEngine._question (tests/test_serving.py checks the two engines render alike).""" instructions = _text(q.get("instructions")) if q["type"] == "noul": criteria = q.get("criteria") or {} options = [_text(criteria.get("true")) or "Yes", _text(criteria.get("false")) or "No"] keys = ["true", "false"] else: keys = list(q["criteria"]) # A criterion without a description (PhishNChips verdict_alt_minimal: {"phishing": null, ...}) is # shown by its key, not as an empty option. options = [_text(q["criteria"][k]) or k for k in keys] if len(options) > MAX_OPTIONS: raise Unsupported(f"{len(options)} options, limit {MAX_OPTIONS}") return instructions, options, keys def _render(self, state, q, questions=None, prefix=None, order=None): """Prompt ids and option keys, exactly as LogitsEngine._render.""" instructions, options, keys = self._question(q) if order is not None: options = [options[i] for i in order] ids = prompt_ids(self.tok, state, instructions, options, self.codes[: len(options)], self.twice, layout=self.layout, questions=questions, prefix=prefix) if len(ids) > self.max_len: raise Unsupported(f"maximum context length {self.max_len} exceeded: {len(ids)} tokens") return ids, keys def _render_request(self, state, questions): """As LogitsEngine._render_request: option keys per question, [(question index, order, ids)], v5 prefix.""" texts = [_text(q.get("instructions")) for q in questions.values()] prefix = request_prefix(self.tok, state, texts, self.layout, self.twice) keys_all, items = [], [] for i, q in enumerate(questions.values()): keys_all.append(self._question(q)[2]) for order in option_orders(len(keys_all[-1]), self.order_average): items.append((i, order, self._render(state, q, texts, prefix, order)[0])) return keys_all, items, prefix def _params_for(self, n): if n not in self._params: self._params[n] = self._sampling(max_tokens=1, temperature=0.0, logprobs=n, allowed_token_ids=list(self.code_ids[:n]), detokenize=False) return self._params[n] def _generate(self, prompts, ns): return self.llm.generate([{"prompt_token_ids": p} for p in prompts], [self._params_for(n) for n in ns], use_tqdm=False) def probabilities(self, state, questions): """Per question: its option keys and probabilities; and the request's input tokens.""" keys_all, items, prefix = self._render_request(state, questions) prompts, ns = [r[2] for r in items], [len(r[1]) for r in items] # v5: the prompts share at least the request prefix (no need to scan them) if self.prefix_caching and len(prompts) > 1 and \ (len(prefix) if prefix is not None else common_prefix(prompts)) >= self.share_min_tokens: outputs = self._generate(prompts[:1], ns[:1]) + self._generate(prompts[1:], ns[1:]) else: outputs = self._generate(prompts, ns) probs = [code_probabilities(read_codes(o, self.code_ids[:n]), self.temperature) for o, n in zip(outputs, ns)] return keys_all, average_orders(len(keys_all), items, probs), sum(len(p) for p in prompts) def __call__(self, state, questions): state = _text(state) option_keys, probs_all, tokens = self.probabilities(state, questions) answers = {} for i, key in enumerate(questions): q_type, opt_keys, probs = questions[key]["type"], option_keys[i], probs_all[i] if q_type == "noul": answers[key] = {"type": "noul", "noul": probs[0]} else: dist = dict(zip(opt_keys, probs)) answers[key] = {"type": "choice", "choice": max(dist, key=dist.get), "probabilities": dist} return {"model": self.name, "answers": answers, "usage": {"input_tokens": tokens}}, None def runtime(self): info = {} try: import torch import transformers import vllm info = {"vllm": vllm.__version__, "torch": torch.__version__, "transformers": transformers.__version__} config = self.llm.llm_engine.vllm_config info["attention_backend"] = str(config.attention_config.backend) info["flash_attn_version"] = config.attention_config.flash_attn_version info["quantization"] = config.model_config.quantization info["kv_cache_dtype"] = config.cache_config.cache_dtype except Exception as exc: # noqa: BLE001 - runtime info is best effort info["runtime_error"] = f"{type(exc).__name__}: {exc}" return info def close(self): llm, self.llm = getattr(self, "llm", None), None if llm is not None: try: llm.llm_engine.engine_core.shutdown() except Exception: # noqa: BLE001 - older/newer engine layouts; the process exit cleans up anyway pass