evalradar 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,399 @@
1
+ """vLLM capture adapter (prototype): passive forward hooks inside an offline `vllm.LLM` engine.
2
+
3
+ Scope: `last_prefill` capture of `resid_post`, `mixer_out` and `mlp_out` for the Qwen2 layout, greedy
4
+ decoding, one GPU, eager mode. Everything else raises a typed error. Importing this module does not
5
+ import vLLM or torch; `VLLMCaptureAdapter.load` does.
6
+
7
+ How the vLLM model differs from the HF one, and what this adapter does about it (each point was
8
+ checked numerically against HFModelAdapter):
9
+
10
+ * A vLLM Qwen2 decoder layer returns `(hidden_states, residual)`; the residual add is fused into the
11
+ next layer's RMSNorm (and into the final norm). HF's `resid_post` of layer l is therefore
12
+ `hidden_states + residual` of layer l's output, which the hook computes in the model dtype (the
13
+ same bfloat16 rounding as HF's own add).
14
+ * vLLM runs all scheduled tokens of all requests as one flat `[num_tokens, d]` tensor. The hook maps
15
+ rows to requests from the GPU model runner's per-step bookkeeping (`input_batch.req_ids`,
16
+ `num_computed_tokens_cpu`, `num_prompt_tokens`, and the per-request scheduled token counts), so a
17
+ request's last prompt token is found even when prompts are prefilled in chunks or next to decode
18
+ tokens of other requests. The last prompt token ID seen by the hook is checked against the prompt.
19
+ * Hooks only fire when modules are actually called. CUDA graphs and torch.compile bypass Python
20
+ module calls, so the engine runs with `enforce_eager=True`.
21
+ * Hooks must live in the process that runs the model. This adapter sets
22
+ `VLLM_ENABLE_V1_MULTIPROCESSING=0` and installs the hooks through `LLM.collective_rpc` with a
23
+ callable, which on the single-process executor runs in this process and receives the worker.
24
+ * Prefix caching is disabled: a cached prefix is not recomputed, so its states never pass the hooks.
25
+ (The last prompt token is always recomputed by vLLM, so `last_prefill` would survive, but this was
26
+ not tested.)
27
+
28
+ Hooks never modify outputs and never raise into the model; a violated assumption marks the affected
29
+ requests as failed (`GenerationTrace.capture_error`), generation continues.
30
+ """
31
+ from __future__ import annotations
32
+ from dataclasses import dataclass
33
+ from pathlib import Path
34
+ from typing import Sequence
35
+ import os
36
+ import time
37
+
38
+ from ..contracts import Capture, CaptureError, CaptureSpec, UnavailableError, UnsupportedError, available_feature_ids, digest
39
+ from ..core import Fingerprint
40
+ from .hf import GenerationTrace, sha256_file
41
+
42
+ # vLLM module layout per HF model_type: where the decoder layers live and the block attributes for taps.
43
+ VLLM_LAYOUTS = {
44
+ "qwen2": {"architecture": "Qwen2ForCausalLM", "layers": "model.layers", "mixer": "self_attn", "mlp": "mlp"},
45
+ }
46
+ SUPPORTED_POLICIES = ("last_prefill",)
47
+
48
+
49
+ def _resolve(root, path: str):
50
+ for part in path.split("."):
51
+ root = getattr(root, part)
52
+ return root
53
+
54
+
55
+ _LOCAL_WORKERS: list = []
56
+
57
+
58
+ def _rpc_register_local_worker(worker):
59
+ """Runs via LLM.collective_rpc. Top level, so it is pickled by reference and runs in this module."""
60
+ _LOCAL_WORKERS.append(worker)
61
+ return os.getpid()
62
+
63
+
64
+ @dataclass
65
+ class _StepView:
66
+ """Rows of the flat token tensor that hold some request's last prompt token in this step."""
67
+ rows: list # flat row indices
68
+ req_ids: list # vLLM internal request IDs, aligned with rows
69
+ positions: list # absolute position of the last prompt token, aligned with rows
70
+ num_tokens: int = 0
71
+ idx: object = None # rows as a device tensor
72
+
73
+
74
+ class _HookState:
75
+ """Shared between the hooks (worker side) and the adapter. Same process by construction."""
76
+
77
+ def __init__(self):
78
+ self.active = False
79
+ self.specs: tuple = ()
80
+ self.store: dict = {} # (vllm_req_id, layer, tap) -> tensor [d]
81
+ self.debug: dict = {} # (vllm_req_id, layer) -> hidden_states alone, for resid_post
82
+ self.keep_debug = False
83
+ self.errors: dict = {} # vllm_req_id or "*" -> reason
84
+ self.view: _StepView | None = None
85
+ self.row_checks: dict = {} # vllm_req_id -> (input token id, position) tensors at the captured row, expected position
86
+ self.steps = 0
87
+ self.max_tokens_in_step = 0
88
+ self.max_reqs_in_step = 0
89
+ self.split_prefills = 0
90
+ self.mixed_steps = 0 # steps that held prefill rows next to decode rows
91
+
92
+ def fail(self, key: str, reason: str):
93
+ self.errors.setdefault(key, reason)
94
+
95
+
96
+ class VLLMCaptureAdapter:
97
+ """Offline vLLM engine with passive last-prompt-position capture. One instance per process."""
98
+
99
+ def __init__(self, llm, *, model_id: str, revision: str, file_hashes: dict, settings: dict, model_type: str):
100
+ self.llm = llm
101
+ self.model_id, self.revision, self.file_hashes = model_id, revision, dict(file_hashes)
102
+ self.settings = dict(settings)
103
+ self.layout = VLLM_LAYOUTS[model_type]
104
+ self.dtype = settings["dtype"]
105
+ self.tokenizer = llm.get_tokenizer()
106
+ self._state = _HookState()
107
+ self.last_step_stats: dict = {}
108
+ self._install_hooks()
109
+
110
+ # ------------------------------------------------------------------------------------- loading
111
+ @classmethod
112
+ def load(cls, snapshot_dir: str | Path, *, model_id: str, revision: str, dtype: str = "bfloat16",
113
+ gpu_memory_utilization: float = 0.25, max_model_len: int = 1024, max_num_seqs: int = 64,
114
+ max_num_batched_tokens: int | None = None, seed: int = 0, attention_backend: str | None = None) -> "VLLMCaptureAdapter":
115
+ """Load from a local directory only (no hub access, no remote code), single GPU, eager mode."""
116
+ import json
117
+ snapshot_dir = Path(snapshot_dir)
118
+ config = json.loads((snapshot_dir / "config.json").read_text())
119
+ model_type = config.get("model_type")
120
+ if model_type not in VLLM_LAYOUTS:
121
+ raise UnsupportedError(f"architecture not in the verified vLLM layout allowlist: {model_type!r}")
122
+ # The hooks have to run in this process: in-process engine core, single-process executor.
123
+ os.environ["VLLM_ENABLE_V1_MULTIPROCESSING"] = "0"
124
+ os.environ.setdefault("HF_HUB_OFFLINE", "1")
125
+ os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
126
+ import vllm
127
+ settings = {"vllm": vllm.__version__, "dtype": dtype, "enforce_eager": True, "enable_prefix_caching": False,
128
+ "tensor_parallel_size": 1, "pipeline_parallel_size": 1, "max_model_len": max_model_len,
129
+ "max_num_seqs": max_num_seqs, "max_num_batched_tokens": max_num_batched_tokens or max(max_model_len, 8192),
130
+ "gpu_memory_utilization": gpu_memory_utilization, "seed": seed, "generation_config": "vllm",
131
+ "multiprocessing": False, "attention_backend": attention_backend or "auto"}
132
+ llm = vllm.LLM(model=str(snapshot_dir), tokenizer=str(snapshot_dir), dtype=dtype, trust_remote_code=False,
133
+ enforce_eager=True, enable_prefix_caching=False, tensor_parallel_size=1, seed=seed,
134
+ gpu_memory_utilization=gpu_memory_utilization, max_model_len=max_model_len,
135
+ max_num_seqs=max_num_seqs, max_num_batched_tokens=settings["max_num_batched_tokens"],
136
+ generation_config="vllm", **({"attention_backend": attention_backend} if attention_backend else {}))
137
+ hashes = {p.name: sha256_file(p) for p in sorted(snapshot_dir.iterdir())
138
+ if p.is_file() and p.suffix in (".json", ".jinja", ".safetensors")}
139
+ out = cls(llm, model_id=model_id, revision=revision, file_hashes=hashes, settings=settings, model_type=model_type)
140
+ out.settings["attention_backend_resolved"] = out._attention_backend_name()
141
+ return out
142
+
143
+ def _local_worker(self):
144
+ """The worker object that runs the model, from this process.
145
+
146
+ `LLM.collective_rpc` serializes a callable even on the in-process executor, so a closure would
147
+ install hooks into a copy of the capture state. A top-level function is pickled by reference;
148
+ it hands the real worker back through a module global, and the hooks are installed here."""
149
+ _LOCAL_WORKERS.clear()
150
+ pids = self.llm.collective_rpc(_rpc_register_local_worker)
151
+ if pids != [os.getpid()] or len(_LOCAL_WORKERS) != 1:
152
+ raise UnsupportedError(f"the model runs in another process (worker pids {pids}); capture needs the "
153
+ "single-process executor with VLLM_ENABLE_V1_MULTIPROCESSING=0 and one GPU")
154
+ return _LOCAL_WORKERS.pop()
155
+
156
+ def _attention_backend_name(self) -> str:
157
+ try:
158
+ layer = _resolve(self._worker.model_runner.get_model(), self.layout["layers"])[0]
159
+ return type(layer.self_attn.attn.impl).__name__
160
+ except Exception as exc:
161
+ return f"unknown:{type(exc).__name__}"
162
+
163
+ # --------------------------------------------------------------------------------------- hooks
164
+ def _install_hooks(self):
165
+ state, layout = self._state, self.layout
166
+ import torch
167
+
168
+ def install(worker):
169
+ runner = worker.model_runner
170
+ model = runner.get_model()
171
+ if type(model).__name__ != layout["architecture"]:
172
+ raise UnsupportedError(f"expected {layout['architecture']}, got {type(model).__name__}")
173
+ layers = _resolve(model, layout["layers"])
174
+ handles = []
175
+
176
+ def build_view(ib):
177
+ """Rows of this step's flat token tensor that hold some request's last prompt token.
178
+
179
+ vLLM's V2 GPU runner orders requests within a step by its own rule (decodes first), so
180
+ the mapping uses the step's InputBatch: req_ids in batch order, query_start_loc, the
181
+ tokens computed before this step, and each request's prompt length."""
182
+ n = ib.num_reqs
183
+ qsl = ib.query_start_loc_np
184
+ computed = ib.num_computed_tokens_np
185
+ prompt = runner.req_states.prompt_len.np[ib.idx_mapping_np]
186
+ rows, rids, positions = [], [], []
187
+ has_prefill = has_decode = False
188
+ for i in range(n):
189
+ c, p, lo, hi = int(computed[i]), int(prompt[i]), int(qsl[i]), int(qsl[i + 1])
190
+ if c < p:
191
+ has_prefill = True
192
+ if c > 0 and c + (hi - lo) >= p:
193
+ state.split_prefills += 1 # last chunk of a prompt prefilled in several steps
194
+ if c + (hi - lo) >= p: # this chunk contains the last prompt token
195
+ rows.append(lo + (p - 1 - c)); rids.append(ib.req_ids[i]); positions.append(p - 1)
196
+ else:
197
+ has_decode = True
198
+ state.mixed_steps += int(has_prefill and has_decode)
199
+ state.max_tokens_in_step = max(state.max_tokens_in_step, int(ib.num_tokens))
200
+ state.max_reqs_in_step = max(state.max_reqs_in_step, n)
201
+ view = _StepView(rows, rids, positions)
202
+ view.num_tokens = int(ib.num_tokens)
203
+ if rows:
204
+ view.idx = torch.tensor(rows, device=ib.input_ids.device)
205
+ # Checked after generation (no sync here): the token and position the model read at each row.
206
+ ids, pos = ib.input_ids.index_select(0, view.idx), ib.positions.index_select(0, view.idx)
207
+ for k, rid in enumerate(rids):
208
+ state.row_checks[rid] = (ids[k], pos[k], positions[k])
209
+ return view
210
+
211
+ def make_hook(layer: int, tap: str):
212
+ def hook(_module, _args, output):
213
+ try:
214
+ if not state.active:
215
+ return None
216
+ view = state.view
217
+ if view is None or not view.rows:
218
+ return None
219
+ if tap == "resid_post":
220
+ if not (isinstance(output, tuple) and len(output) == 2):
221
+ return state.fail("*", "unexpected_decoder_layer_output")
222
+ hidden, residual = output
223
+ h = hidden if residual is None else hidden + residual # model dtype, like HF's add
224
+ else:
225
+ h = output[0] if isinstance(output, tuple) else output
226
+ hidden = None
227
+ if h.ndim != 2 or h.shape[0] < view.num_tokens:
228
+ return state.fail("*", "unexpected_flat_token_shape")
229
+ dtype = str(h.dtype).removeprefix("torch.")
230
+ sel = h.index_select(0, view.idx).detach().clone()
231
+ dbg = hidden.index_select(0, view.idx).detach().clone() if (state.keep_debug and hidden is not None) else None
232
+ for k, rid in enumerate(view.req_ids):
233
+ for s in state.specs:
234
+ if (s.layer, s.tap) != (layer, tap):
235
+ continue
236
+ if dtype != s.dtype:
237
+ state.fail(rid, f"dtype_mismatch:{dtype}!={s.dtype}")
238
+ continue
239
+ if (rid, layer, tap) in state.store:
240
+ state.fail(rid, "last_prompt_position_seen_twice")
241
+ state.store[(rid, layer, tap)] = sel[k]
242
+ if dbg is not None:
243
+ state.debug[(rid, layer)] = dbg[k]
244
+ except Exception as exc: # passive: never break generation because of monitoring
245
+ state.fail("*", f"hook_error:{type(exc).__name__}:{exc}")
246
+ return None
247
+ return hook
248
+
249
+ modules = {}
250
+ for i, block in enumerate(layers):
251
+ modules[(i, "resid_post")] = block
252
+ modules[(i, "mixer_out")] = getattr(block, layout["mixer"])
253
+ modules[(i, "mlp_out")] = getattr(block, layout["mlp"])
254
+ for key, mod in modules.items():
255
+ handles.append(mod.register_forward_hook(make_hook(*key)))
256
+
257
+ # Per-step bookkeeping: the runner builds one InputBatch per step right before the forward.
258
+ orig = runner.prepare_inputs
259
+
260
+ def prepare_inputs(*a, **kw):
261
+ ib = orig(*a, **kw)
262
+ state.view = None
263
+ if state.active:
264
+ try:
265
+ state.steps += 1
266
+ state.view = build_view(ib)
267
+ except Exception as exc:
268
+ state.fail("*", f"step_view_error:{type(exc).__name__}:{exc}")
269
+ return ib
270
+
271
+ runner.prepare_inputs = prepare_inputs
272
+ return len(layers)
273
+
274
+ self._worker = self._local_worker()
275
+ self.num_layers = install(self._worker)
276
+
277
+ # ----------------------------------------------------------------------------------- identity
278
+ def backend(self) -> str:
279
+ """Runtime identity. Differs from every HF backend string, so a monitor validated on HF is
280
+ refused here until it is revalidated on this backend."""
281
+ import torch
282
+ s = self.settings
283
+ return (f"vllm-{s['vllm']};torch-{torch.__version__};vllm-offline-greedy;device:{torch.cuda.get_device_name(0)};"
284
+ f"exec:engine=vllm-continuous-batching,enforce_eager={s['enforce_eager']},prefix_caching={s['enable_prefix_caching']},"
285
+ f"tp={s['tensor_parallel_size']},pp={s['pipeline_parallel_size']},max_num_seqs={s['max_num_seqs']},"
286
+ f"max_num_batched_tokens={s['max_num_batched_tokens']},attn={s.get('attention_backend_resolved', s['attention_backend'])}")
287
+
288
+ def fingerprint(self, specs: Sequence[CaptureSpec], *, generation: dict, horizon: str) -> Fingerprint:
289
+ """Same field recipe as HFModelAdapter.fingerprint, so only `backend` differs for the same model."""
290
+ weights = {k: v for k, v in self.file_hashes.items() if k.endswith(".safetensors")}
291
+ tok = {k: v for k, v in self.file_hashes.items() if k.startswith("tokenizer") or k.endswith(".jinja")}
292
+ return Fingerprint(
293
+ model=self.model_id,
294
+ checkpoint=f"revision:{self.revision};weights:{digest(weights)}",
295
+ tokenizer=f"files:{digest(tok)}",
296
+ backend=self.backend(),
297
+ quantization=f"none;dtype:{self.dtype}",
298
+ adapter="none",
299
+ config=f"config.json:{self.file_hashes.get('config.json', 'unknown')};generation:{digest(generation)}",
300
+ feature_spec=f"horizon:{horizon};captures:{digest(sorted(s.digest for s in specs))}",
301
+ )
302
+
303
+ def encode_chat(self, messages, **template_kwargs) -> list[int]:
304
+ ids = self.tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, **template_kwargs)
305
+ if not isinstance(ids, list):
306
+ ids = ids["input_ids"]
307
+ return [int(t) for t in ids]
308
+
309
+ # --------------------------------------------------------------------------------- generation
310
+ def _check_specs(self, specs: Sequence[CaptureSpec]):
311
+ available_feature_ids(specs)
312
+ for s in specs:
313
+ if s.layer is None:
314
+ raise UnsupportedError("this adapter requires an explicit layer index")
315
+ if s.layer >= self.num_layers:
316
+ raise UnsupportedError(f"layer {s.layer} out of range for {self.num_layers} layers")
317
+ if s.position_policy not in SUPPORTED_POLICIES:
318
+ raise UnsupportedError(f"vLLM backend supports {SUPPORTED_POLICIES} only, not {s.position_policy!r}")
319
+ if s.dtype != self.dtype:
320
+ raise UnsupportedError(f"spec dtype {s.dtype} differs from engine dtype {self.dtype}")
321
+
322
+ def generate_batch(self, prompts: Sequence[Sequence[int]], *, request_ids: Sequence[str], max_new_tokens: int,
323
+ eos_token_ids: Sequence[int], repetition_penalty: float = 1.0, specs: Sequence[CaptureSpec] = (),
324
+ fingerprint_digest: str = "", debug_layer_outputs: bool = False) -> list[GenerationTrace]:
325
+ """Greedy generation for token-ID prompts, submitted together (vLLM schedules them with
326
+ continuous batching). Returns one trace per request, in order. `elapsed_s` is the call's wall time."""
327
+ from vllm import SamplingParams
328
+ from vllm.inputs import TokensPrompt
329
+ import torch
330
+ if not prompts or len(prompts) != len(request_ids) or len(set(request_ids)) != len(request_ids):
331
+ raise UnsupportedError("need one unique request ID per prompt")
332
+ if min(len(p) for p in prompts) < 1:
333
+ raise UnsupportedError("empty prompt")
334
+ if max(len(p) for p in prompts) + max_new_tokens > self.settings["max_model_len"]:
335
+ raise UnsupportedError("prompt plus new tokens exceeds max_model_len")
336
+ self._check_specs(specs)
337
+ eos = [int(e) for e in eos_token_ids]
338
+ params = SamplingParams(temperature=0.0, max_tokens=max_new_tokens, stop_token_ids=eos, repetition_penalty=repetition_penalty,
339
+ skip_special_tokens=True, detokenize=False)
340
+ st = self._state
341
+ st.specs, st.store, st.debug, st.errors, st.row_checks, st.view = tuple(specs), {}, {}, {}, {}, None
342
+ st.keep_debug = debug_layer_outputs
343
+ st.steps = st.mixed_steps = st.split_prefills = st.max_tokens_in_step = st.max_reqs_in_step = 0
344
+ st.active = bool(specs)
345
+ torch.cuda.synchronize()
346
+ start = time.perf_counter()
347
+ try:
348
+ outs = self.llm.generate([TokensPrompt(prompt_token_ids=list(map(int, p))) for p in prompts], params, use_tqdm=False)
349
+ finally:
350
+ st.active = False
351
+ torch.cuda.synchronize()
352
+ elapsed = time.perf_counter() - start
353
+ self.last_step_stats = {"engine_steps": st.steps, "steps_with_prefill_and_decode_rows": st.mixed_steps,
354
+ "max_tokens_in_step": st.max_tokens_in_step,
355
+ "prompts_prefilled_in_several_chunks": st.split_prefills, "max_requests_in_step": st.max_reqs_in_step}
356
+ # The engine runs a request under "<external id>-<random suffix>"; outputs carry the external id.
357
+ by_external: dict = {}
358
+ for internal in st.row_checks:
359
+ by_external.setdefault(internal.rsplit("-", 1)[0], []).append(internal)
360
+ traces = []
361
+ for prompt, rid, out in zip(prompts, request_ids, outs):
362
+ if list(out.prompt_token_ids) != list(prompt):
363
+ raise CaptureError("vLLM returned outputs out of order")
364
+ comp = out.outputs[0]
365
+ new = tuple(int(t) for t in comp.token_ids)
366
+ trace = GenerationTrace(rid, len(prompt), new, elapsed, batch_size=len(prompts)) # keeps EOS, like HF
367
+ internal = by_external.get(out.request_id, [])
368
+ vid = internal[0] if len(internal) == 1 else None
369
+ err = st.errors.get("*") or st.errors.get(vid)
370
+ if specs and err is None and len(internal) > 1:
371
+ err = "ambiguous_internal_request_id"
372
+ if specs and err is None:
373
+ try:
374
+ trace.captures = self._captures(vid, rid, prompt, specs, fingerprint_digest)
375
+ except (CaptureError, UnavailableError) as exc:
376
+ err = f"{exc.state}:{exc}"
377
+ elif err is not None:
378
+ err = f"error:{err}"
379
+ trace.capture_error = err
380
+ if debug_layer_outputs:
381
+ trace.debug = {s.layer: {"hidden_only": st.debug.get((vid, s.layer))} for s in specs if s.tap == "resid_post"}
382
+ traces.append(trace)
383
+ return traces
384
+
385
+ def _captures(self, vid, rid, prompt, specs, fingerprint_digest) -> dict:
386
+ out = {}
387
+ plen = len(prompt)
388
+ check = self._state.row_checks.get(vid)
389
+ if check is None:
390
+ raise UnavailableError("last prompt position never reached the hooks")
391
+ tok, pos, want = check
392
+ if int(tok) != int(prompt[-1]) or int(pos) != plen - 1 or want != plen - 1:
393
+ raise CaptureError("captured row does not hold the last prompt token at position prompt_len - 1")
394
+ for s in specs:
395
+ t = self._state.store.get((vid, s.layer, s.tap))
396
+ if t is None:
397
+ raise UnavailableError(f"no state captured for {s.feature_id}")
398
+ out[s.feature_id] = Capture(rid, s, fingerprint_digest, plen, (plen - 1,), ("prefill",), t.unsqueeze(0))
399
+ return out