File size: 13,399 Bytes
8c587c9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 | """Label-blind, single-token vLLM engine for the official Decision Index runner."""
from __future__ import annotations
import hashlib
import importlib.metadata
import json
import math
import os
from pathlib import Path
from typing import TYPE_CHECKING
from decision_index.engines.base import Engine, Unsupported
from native_prompt import prompt_for_field
if TYPE_CHECKING:
from torch import nn
from transformers import PretrainedConfig
def configure_decision_attention(config: PretrainedConfig) -> PretrainedConfig:
"""Select vLLM's official bidirectional full-attention implementation."""
config.get_text_config().is_causal = False
return config
def llm_options(model: str, max_model_len: int = 32768, max_num_seqs: int = 64) -> dict:
"""Use identical vLLM arguments for configuration preflight and inference."""
return dict(
model=model, tokenizer=model, dtype="bfloat16", tensor_parallel_size=1,
safetensors_load_strategy="eager",
hf_overrides=configure_decision_attention,
max_model_len=int(max_model_len), max_num_batched_tokens=int(max_model_len),
max_num_seqs=int(max_num_seqs), enable_prefix_caching=False, enable_chunked_prefill=False,
enforce_eager=True, gpu_memory_utilization=0.80, max_logprobs=255,
async_scheduling=False,
logprobs_mode="processed_logits", limit_mm_per_prompt={"image": 0, "video": 0},
seed=20261023,
)
def inspect_model_attention(model: nn.Module) -> dict[str, object]:
"""Verify the loaded model uses upstream attention without method replacement."""
from vllm.v1.attention.backend import AttentionType
full = linear = 0
backends = set()
for layer in model.language_model.model.layers:
if layer.layer_type == "full_attention":
attention = layer.self_attn.attn
if attention.attn_type != AttentionType.ENCODER_ONLY:
raise ValueError("Full attention must be bidirectional")
if not attention.forward.__func__.__module__.startswith("vllm."):
raise ValueError("Unexpected custom attention forward")
backends.add(type(attention.impl).__name__)
full += 1
elif layer.layer_type == "linear_attention":
if not type(layer.linear_attn).__module__.startswith("vllm."):
raise ValueError("Unexpected custom Gated DeltaNet implementation")
linear += 1
if full != 16 or linear != 48:
raise ValueError("Unexpected model layer counts")
return {"passed": True, "check": "loaded upstream attention configuration",
"bidirectional_full_attention_layers": full, "stock_linear_attention_layers": linear,
"backends": sorted(backends), "custom_attention_forward": False}
class DecisionVllmEngine(Engine):
"""Preserve native prompts, option order and complete candidate probabilities."""
name = "flyai-decision-vllm"
def __init__(self, model: str, codebook: str, max_model_len: int = 32768,
max_num_seqs: int = 64, **options):
super().__init__(**options)
os.environ["VLLM_ENABLE_V1_MULTIPROCESSING"] = "0"
import torch
from vllm import LLM
if importlib.metadata.version("vllm").split("+")[0] != "0.31.0":
raise RuntimeError("This engine is pinned to vLLM 0.31.0")
if torch.cuda.device_count() != 1:
raise ValueError("This engine requires exactly one visible GPU")
self.audit_dir = Path(options["audit_dir"]) if options.get("audit_dir") else None
self.model_path = model
self.max_model_len = int(max_model_len)
self.codebook = json.loads(Path(codebook).read_text())
self.llm = LLM(**llm_options(model, self.max_model_len, max_num_seqs))
attention_checks = self.llm.apply_model(inspect_model_attention)
if len(attention_checks) != 1:
raise ValueError("Expected one model worker")
if self.audit_dir:
(self.audit_dir / "attention-config-check.json").write_text(
json.dumps(attention_checks[0], indent=2) + "\n")
self.tokenizer = self.llm.get_tokenizer()
for alias, token in zip(self.codebook["keys"], self.codebook["token_ids"], strict=True):
if self.tokenizer.encode(alias, add_special_tokens=False) != [token]:
raise ValueError("Codebook token identity mismatch")
self.input_tokens = 0
self.maximum_input_tokens = 0
self.self_check = {}
self.provenance = {
"model": model, "native_step": 1139, "full_attention": "bidirectional",
"linear_attention": "unchanged causal GDN", "prefix_cache": False,
"chunked_prefill": False, "mtp": 0, "readout": "last real token; FP32 candidate softmax",
"codebook_sha256": hashlib.sha256(Path(codebook).read_bytes()).hexdigest(),
"engine_processes": 1, "tensor_parallel_size": 1, "max_num_seqs": int(max_num_seqs),
}
def __call__(self, state, questions):
"""Build independent field prompts, then return every supplied candidate."""
import torch
from vllm import SamplingParams
payload = {"state": state, "questions": questions}
prompts, params, fields = [], [], []
alias_tokens = dict(zip(self.codebook["keys"], self.codebook["token_ids"]))
for field, question in questions.items():
if question["type"] not in ("choice", "noul"):
raise Unsupported(f"Unsupported question type: {question['type']}")
if question["type"] == "choice" and len(question["criteria"]) > 255:
raise Unsupported("At most 255 options per choice; no options were dropped")
prompt, mapping, _ = prompt_for_field(self.tokenizer, payload, field, self.codebook)
ids = self.tokenizer.encode(prompt, add_special_tokens=False)
if not 0 < len(ids) < self.max_model_len:
raise Unsupported(f"Input length {len(ids)} exceeds capacity; no truncation")
tokens = [alias_tokens[alias] for alias in mapping.values()]
prompts.append({"prompt_token_ids": ids})
params.append(SamplingParams(temperature=0, max_tokens=1, ignore_eos=True,
detokenize=False, allowed_token_ids=tokens, logprobs=len(tokens)))
fields.append((field, question, mapping, tokens))
self.input_tokens += len(ids)
self.maximum_input_tokens = max(self.maximum_input_tokens, len(ids))
outputs = self.llm.generate(prompts, params, use_tqdm=False)
answers = {}
for (field, question, mapping, tokens), output in zip(fields, outputs, strict=True):
logits = output.outputs[0].logprobs[0]
selected = [logits[token].logprob for token in tokens]
if not all(math.isfinite(value) for value in selected):
raise ValueError("Nonfinite candidate logits")
values = torch.tensor(selected, dtype=torch.float32).softmax(-1).tolist()
probabilities = dict(zip(mapping, values))
if question["type"] == "noul":
answers[field] = {"type": "noul", "noul": probabilities["true"]}
else:
answers[field] = {"type": "choice", "choice": max(probabilities, key=probabilities.get),
"probabilities": probabilities}
return {"model": "FlyAI-Decision-27B", "answers": answers}, None
def _check_batch_isolation(self) -> dict[str, object]:
"""Compare heterogeneous fields alone, in a mixed batch and in reverse order."""
from decision_index.engines.base import validate
state = "The parcel is blue, weighs seven kilograms, and arrived on Tuesday. Its seal is intact."
templates = [
{"type": "choice", "instructions": "Choose the parcel color.",
"criteria": {"red": "red", "blue": "blue"}},
{"type": "choice", "instructions": "Choose its weight in kilograms.",
"criteria": {"two": "2", "seven": "7", "nine": "9"}},
{"type": "choice", "instructions": "Choose its arrival day.",
"criteria": {"Monday": "Monday", "Tuesday": "Tuesday", "Friday": "Friday"}},
{"type": "noul", "instructions": "Is the seal intact?"},
{"type": "choice", "instructions": "Choose the statement supported by the parcel record.",
"criteria": {"damaged": "The seal is broken", "heavy": "It weighs seven kilograms",
"green": "It is green", "late": "It arrived on Friday"}},
{"type": "noul", "instructions": "Did the parcel arrive on Friday?"},
]
questions = {}
for index in range(64):
question = dict(templates[index % len(templates)])
question["instructions"] += f" Check {index}." + " Use only the parcel record." * (index % 8)
if question["type"] == "choice":
items = list(question["criteria"].items())
question["criteria"] = dict(reversed(items) if index % 2 else items)
questions[f"field_{index}"] = question
payload = {"state": state, "questions": questions}
rendered = [prompt_for_field(self.tokenizer, payload, field, self.codebook)[0] for field in questions]
if len(set(rendered)) != len(questions):
raise RuntimeError("Batch isolation audit requires distinct prompts")
singles = {}
for field, question in questions.items():
response, _ = self(state, {field: question})
validate({field: question}, response)
singles[field] = response["answers"][field]
deltas = {}
disagreements = {}
for label, batch in (("mixed", questions), ("reversed", dict(reversed(list(questions.items()))))):
response, _ = self(state, batch)
validate(batch, response)
delta = 0.0
changed = 0
for field, old in singles.items():
new = response["answers"][field]
if old["type"] == "choice":
delta = max(delta, *(abs(value - new["probabilities"][key])
for key, value in old["probabilities"].items()))
changed += old["choice"] != new["choice"]
else:
delta = max(delta, abs(old["noul"] - new["noul"]))
changed += (old["noul"] >= 0.5) != (new["noul"] >= 0.5)
deltas[label] = delta
disagreements[label] = changed
return {"batch_isolation_fields": len(questions), "batch_isolation_distinct_prompts": len(set(rendered)),
"batch_isolation_order_max_probability_delta": deltas,
"batch_isolation_order_decision_disagreements": disagreements,
"single_vs_batch_max_probability_delta": max(deltas.values())}
def warmup(self):
"""Warm generic shapes and audit batch isolation and the 255-option limit."""
from decision_index.engines.base import validate
super().warmup()
isolation = self._check_batch_isolation()
large = {"type": "choice", "instructions": "Select one supplied option.",
"criteria": {f"option_{i}": f"Candidate {i}" for i in range(255)}}
response, _ = self("A generic capability check.", {"choice": large, "boolean": {"type": "noul"}})
validate({"choice": large, "boolean": {"type": "noul"}}, response)
oversized = {**large, "criteria": {f"option_{i}": f"Candidate {i}" for i in range(256)}}
try:
self("A generic capability check.", {"choice": oversized})
except Unsupported:
pass
else:
raise RuntimeError("The 255-option capacity limit was not enforced")
self.self_check = {"candidate_255_coverage": True, "noul_valid": True,
"candidate_256_refused_without_truncation": True,
**isolation,
"consistency_is_blocking": False}
print(json.dumps({"stage": "engine_self_check", **self.self_check}), flush=True)
if self.audit_dir:
(self.audit_dir / "engine-self-check.json").write_text(json.dumps(self.self_check, indent=2) + "\n")
def runtime(self):
"""Record the actual runtime and hardware, not an assumed official GPU."""
import torch
return {"versions": {name: importlib.metadata.version(name) for name in ("torch", "vllm", "transformers")},
"gpu": torch.cuda.get_device_name(0), "gpu_count": torch.cuda.device_count(),
"max_model_len": self.max_model_len, "input_tokens": self.input_tokens,
"maximum_input_tokens": self.maximum_input_tokens, "self_check": self.self_check}
def synchronize(self):
"""Wait for device work before the official wall-time measurement."""
import torch
torch.cuda.synchronize()
def close(self):
"""Persist the final input-capacity and runtime measurements."""
if self.audit_dir:
(self.audit_dir / "engine-final.json").write_text(
json.dumps({"runtime": self.runtime(), "provenance": self.provenance}, indent=2) + "\n")
|