:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ml_inference): bound the serving image's queue and batch JevK5's readout (#106058)
Robbie3ada9d138079
diff --git a/products/ml_inference/packages/kev-vllm/README.md b/products/ml_inference/packages/kev-vllm/README.mdindex 2572790d3607..474994ad9122 100644--- a/products/ml_inference/packages/kev-vllm/README.md+++ b/products/ml_inference/packages/kev-vllm/README.md@@ -44,7 +44,41 @@ The answer is under `data.answers`, in Kev's format for either model, with `dataThe AI gateway states the day counts between the dates in a state when a request sets `date_facts` (PostHog/ai-gateway#505), before any host sees it, so this plugin does no date preprocessing of its own.-Prefix caching is off for both models: vLLM does not enable it for pooling models on hybrid backbones, so every row recomputes its state. Batching across rows and requests still applies.+### Batching++vLLM's scheduler is the request pool, so this package adds none of its own. Each question becomes its own engine request, and every request waits in the engine's in-memory queue. At each step, the scheduler packs waiting rows from all callers into one forward pass, up to `--max-num-batched-tokens` tokens, and splits a row longer than the remainder across steps (chunked prefill). A row is prefill only: it finishes in the step that computes its last token, and it frees its slot in that step. A burst of requests therefore becomes a few full steps, not one step per request.++- No state persists between requests. vLLM's KV and Mamba caches hold only the rows in flight. Prefix caching is off for both models, because vLLM does not enable it for pooling models on hybrid backbones. So each row computes its state again, including the rows of one request that share it.+- `JevK5ForDecision` reads the answer from each row's last token only. A chunked row holds no hidden states between steps, and each step's readout is one matmul for all its rows.+- The token budget does not change throughput. A single row already keeps the GPU's compute busy, so larger steps only make each row wait longer. The entrypoint keeps vLLM's default budget.+- vLLM's queue has no limit by default. When the queue is longer than the gateway's timeout, every request in it fails. `--max-num-queued-tokens` makes vLLM answer 503 when the prefill backlog is full, so a caller can retry elsewhere without delay. Set it to the prefill throughput multiplied by the longest wait you accept.++### Load test on an L4++Measured 2026-09-24 on one L4 (EC2 gr6.4xlarge), vLLM 0.29.0, JevK5 at revision `27d2d6b8` in bf16. The requests are JevBench's public items: 70% one question on a short state (median 178 tokens), 20% one question on a long state (median 1,313 tokens), and 10% three questions on one short state. Closed-loop saturation:++| Token budget | Prefill tokens/s | p90 latency at 32 concurrent |+| ------------------------- | ---------------- | ---------------------------- |+| 2,048 (vLLM's L4 default) | 6,000 to 6,100 | 2.9 s |+| 8,192 | 5,700 to 5,800 | 3.6 s |+| 16,384 | 5,900 to 6,000 | not measured |++A request alone gets about 4,600 tokens/s, and short and long rows saturate at the same rate. The GPU runs at its 72 W power cap during saturation. The readout on the last token matches `AllPool`'s to a median 0.0016 (maximum 0.022, which is inside JevK5's own bf16 noise), at the same throughput.++Open loop at a Poisson arrival rate, with a 10 s client timeout as the gateway uses. "OK" is the answers per second that arrive within the timeout:++| Queue limit | Offered load | OK | Rejected with 503 | Timed out | p99 of answers |+| ------------ | ------------- | ------ | ----------------- | --------- | -------------- |+| none | 0.9x capacity | 11.4/s | 0% | 0% | 3.0 s |+| none | 1.3x | 7.8/s | 0% | 47% | 10.0 s |+| none | 2.0x | 3.3/s | 0% | 86% | 9.9 s |+| 5,815 (1 s) | 0.9x | 10.5/s | 11% | 0% | 1.2 s |+| 11,630 (2 s) | 0.9x | 11.4/s | 4% | 0% | 2.0 s |+| 23,260 (4 s) | 0.9x | 11.9/s | 0% | 0% | 3.8 s |+| 23,260 (4 s) | 1.3x | 13.1/s | 19% | 0% | 4.9 s |+| 23,260 (4 s) | 2.0x | 12.9/s | 49% | 0% | 5.2 s |++Without a limit, overload makes the wait longer than the timeout, and the box answers less than a third of its capacity. With a limit, it keeps answering at capacity and rejects the rest at once. The entrypoint's default on an L4 is about four seconds of its throughput. At that limit, the box rejects nothing below capacity, and the slowest answers under overload arrive in about half the gateway's wait. A T4 serves JevK5 at about 1,270 tokens/s, a fifth of an L4. Kev, on the same backbone, served about 69,000 on an H100. The entrypoint sizes the limit for a T4 as well, and any other GPU needs it set.## Container image@@ -63,6 +97,7 @@ docker run -d --restart always --gpus all --network host --shm-size 8g \- The host network lets s5cmd read the instance role's credentials from the metadata service, and Caddy listens on the host's `PORT`. Keep the port closed to the network and reach it over the tailnet.- The named volume keeps the weights across container restarts; it starts owned by the serving user (uid 10001). A host directory mounted instead must be writable by that user.- `DTYPE=float16` on GPUs without bf16. `MODEL_NAME` (the served name the gateway asks for, default `jevk5-0.2`), `MAX_MODEL_LEN`, `GPU_MEMORY_UTILIZATION`, `PORT` and `VLLM_PORT` override the defaults; extra arguments go to `vllm serve`.+- `MAX_NUM_QUEUED_TOKENS` is vLLM's backlog limit. Unset, the entrypoint uses about four seconds of the GPU's measured prefill, which exists for an L4 and a T4 (see [Load test on an L4](#load-test-on-an-l4)). On any other GPU the container refuses to start until it is set.- The image sets `GLOO_SOCKET_IFNAME=lo`. vLLM otherwise resolves the host name at start-up and fails with "File name too long" where a VPC's DHCP domain makes it 64 characters.`kev-vllm-checkpoint verify <dir>` is the manifest check on its own.diff --git a/products/ml_inference/packages/kev-vllm/bin/serve.sh b/products/ml_inference/packages/kev-vllm/bin/serve.shindex c4dc5494f515..85d0ffccc55f 100755--- a/products/ml_inference/packages/kev-vllm/bin/serve.sh+++ b/products/ml_inference/packages/kev-vllm/bin/serve.sh@@ -11,10 +11,26 @@ MODEL_NAME=${MODEL_NAME:-jevk5-0.2}DTYPE=${DTYPE:-auto}MAX_MODEL_LEN=${MAX_MODEL_LEN:-16384}GPU_MEMORY_UTILIZATION=${GPU_MEMORY_UTILIZATION:-0.85}+MAX_NUM_QUEUED_TOKENS=${MAX_NUM_QUEUED_TOKENS:-}export PORT=${PORT:-8000} VLLM_PORT=${VLLM_PORT:-8001} AWS_REGION=${AWS_REGION:-us-east-1}: "${DECISION_BEARER:?set DECISION_BEARER to the bearer the AI gateway sends}"export DECISION_BEARER+# About four seconds of the GPU's measured prefill (README, "Load test on an L4"), so an overloaded box answers 503+# well inside the gateway's wait. A GPU nobody has measured gets no guess, because a queue longer than the wait turns+# overload into timeouts.+if [ -z "$MAX_NUM_QUEUED_TOKENS" ]; then+ gpu=$(python3 -c 'import torch; print(torch.cuda.get_device_name(0))' 2>/dev/null || true)+ case "$gpu" in+ *L4*) MAX_NUM_QUEUED_TOKENS=24000 ;;+ *T4*) MAX_NUM_QUEUED_TOKENS=5000 ;;+ *)+ echo "no measured queue limit for GPU '${gpu:-unknown}': set MAX_NUM_QUEUED_TOKENS to about four seconds of its prefill tokens" >&2+ exit 1+ ;;+ esac+fi+if ! kev-vllm-checkpoint verify "$MODEL_DIR" >/dev/null 2>&1; thenif [ -z "$MODEL_URI" ]; thenecho "no checkpoint matching its manifest at $MODEL_DIR, and no MODEL_URI to fetch one from" >&2@@ -28,7 +44,8 @@ kev-vllm-checkpoint verify "$MODEL_DIR"# Bash as PID 1 does not pass `docker stop` on to its children.trap 'kill $(jobs -p) 2>/dev/null' TERM INTvllm serve "$MODEL_DIR" --served-model-name "$MODEL_NAME" --host 127.0.0.1 --port "$VLLM_PORT" --dtype "$DTYPE" \- --mamba-ssm-cache-dtype float32 --max-model-len "$MAX_MODEL_LEN" --gpu-memory-utilization "$GPU_MEMORY_UTILIZATION" "$@" &+ --mamba-ssm-cache-dtype float32 --max-model-len "$MAX_MODEL_LEN" --gpu-memory-utilization "$GPU_MEMORY_UTILIZATION" \+ --max-num-queued-tokens "$MAX_NUM_QUEUED_TOKENS" "$@" &caddy run --config /etc/kev-vllm/Caddyfile --adapter caddyfile &status=0diff --git a/products/ml_inference/packages/kev-vllm/kev_vllm/io_processor.py b/products/ml_inference/packages/kev-vllm/kev_vllm/io_processor.pyindex 249505db334f..062b7edd7230 100644--- a/products/ml_inference/packages/kev-vllm/kev_vllm/io_processor.py+++ b/products/ml_inference/packages/kev-vllm/kev_vllm/io_processor.py@@ -4,9 +4,6 @@across requests. `post_process` maps each row's probability vector back onto the question it came from."""-import threading-import time-from collections import dequefrom collections.abc import Sequencefrom transformers import AutoTokenizer@@ -17,40 +14,10 @@ from vllm.plugins.io_processors.interface import IOProcessorfrom vllm.renderers import BaseRendererfrom kev_vllm.kev_compat import SystemOneRequest, encode, output_tokens, rows_of, to_answers, to_record+from kev_vllm.pending import PendingRequests# Serving limits, as kev.serve: the per-branch cap mirrors Jev's window and the base model bounds both.INFER_MAX_STATE, INFER_MAX_BRANCH = 8192, 8192-# A request aborted between pre_process and post_process never collects its entry, so old ones are swept. vLLM has no-# abort hook for IO processors and bounds admission rather than request age, so the age is set far beyond any wait a-# caller survives: the gateway gives up on a request in well under a minute.-PENDING_SWEEP_SIZE, PENDING_MAX_AGE_SECONDS = 10_000, 3600---class PendingRequests[T]:- """What pre_process knew about a request, kept until post_process; vLLM calls both with the same request id and- may run them on executor threads, so every access is serialised."""-- def __init__(self) -> None:- self._entries: dict[str | None, deque[tuple[T, float]]] = {}- self._lock = threading.Lock()-- def put(self, request_id: str | None, value: T) -> None:- with self._lock:- if len(self._entries) > PENDING_SWEEP_SIZE:- cutoff = time.monotonic() - PENDING_MAX_AGE_SECONDS- for stale in [rid for rid, entries in self._entries.items() if entries[0][1] < cutoff]:- del self._entries[stale]- self._entries.setdefault(request_id, deque()).append((value, time.monotonic()))-- def take(self, request_id: str | None) -> T:- with self._lock:- entries = self._entries.get(request_id)- if not entries:- raise ValueError(f"request {request_id} waited longer than {PENDING_MAX_AGE_SECONDS}s and was swept")- value, _ = entries.popleft()- if not entries:- del self._entries[request_id]- return valueclass KevIOProcessor(IOProcessor[SystemOneRequest, dict]):diff --git a/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5.py b/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5.pyindex 22fa5b84581c..baa39aa551d5 100644--- a/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5.py+++ b/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5.py@@ -11,6 +11,8 @@ import mathfrom collections.abc import Sequencefrom dataclasses import dataclass+from transformers import PreTrainedTokenizerBase+from kev_vllm.kev_compat import JSONContent, Noul, Question, ScoreLETTERS = "ABCDEFGHIJKLMNOP"@@ -57,7 +59,7 @@ def messages(state: JSONContent, question: Question) -> list[dict[str, str]]:]-def prompt_ids(tokenizer, state: JSONContent, question: Question) -> list[int]:+def prompt_ids(tokenizer: PreTrainedTokenizerBase, state: JSONContent, question: Question) -> list[int]:prompt = tokenizer.apply_chat_template(messages(state, question), tokenize=False, add_generation_prompt=True, enable_thinking=False)ids = tokenizer.encode(prompt, add_special_tokens=False)if len(ids) > MAX_INPUT_TOKENS:@@ -65,7 +67,7 @@ def prompt_ids(tokenizer, state: JSONContent, question: Question) -> list[int]:return ids-def letter_token_ids(tokenizer) -> list[int]:+def letter_token_ids(tokenizer: PreTrainedTokenizerBase) -> list[int]:ids = [tokenizer.encode(letter, add_special_tokens=False) for letter in LETTERS]if any(len(letter_ids) != 1 for letter_ids in ids):raise ValueError("every answer letter must be one token")diff --git a/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5_export.py b/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5_export.pyindex e0fbec30a1f6..34c2404f9f7a 100644--- a/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5_export.py+++ b/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5_export.py@@ -43,7 +43,7 @@ FILES = []-def export(repo: str, revision: str, out: Path) -> dict:+def export(repo: str, revision: str, out: Path) -> dict[str, object]:if not re.fullmatch(r"[0-9a-f]{40}", revision):raise ValueError("pin a full 40-character commit, not a branch or tag")out.mkdir(parents=True, exist_ok=True)diff --git a/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5_io_processor.py b/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5_io_processor.pyindex 1403dc2b9e1b..0043760d5d26 100644--- a/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5_io_processor.py+++ b/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5_io_processor.py@@ -14,8 +14,8 @@ from vllm.plugins.io_processors.interface import IOProcessorfrom vllm.renderers import BaseRendererfrom kev_vllm import jevk5-from kev_vllm.io_processor import PendingRequestsfrom kev_vllm.kev_compat import Question, SystemOneRequest, output_tokens, to_answers, to_record+from kev_vllm.pending import PendingRequestsclass JevK5IOProcessor(IOProcessor[SystemOneRequest, dict]):diff --git a/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5_model.py b/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5_model.pyindex 2969a9ed9318..d3990f9faae2 100644--- a/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5_model.py+++ b/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5_model.py@@ -11,7 +11,6 @@ from collections.abc import Set as AbstractSetimport torchfrom vllm.config import VllmConfigfrom vllm.model_executor.layers.pooler import Pooler, PoolingParamsUpdate-from vllm.model_executor.layers.pooler.tokwise import AllPoolfrom vllm.model_executor.models.interfaces_base import default_pooling_typefrom vllm.model_executor.models.qwen3_5 import Qwen3_5ForCausalLMfrom vllm.tasks import PoolingTask@@ -24,7 +23,6 @@ class JevK5Pooler(Pooler):super().__init__()self.lm_head = lm_headself.letter_token_ids = letter_token_ids- self.all_pool = AllPool()def get_supported_tasks(self) -> AbstractSet[PoolingTask]:return {"plugin"}@@ -33,10 +31,11 @@ class JevK5Pooler(Pooler):return PoolingParamsUpdate()def forward(self, hidden_states: torch.Tensor, pooling_metadata: PoolingMetadata) -> PoolerOutput:- rows = self.all_pool(hidden_states, pooling_metadata)+ # Rows still mid-prefill get an output too, which the model runner discards.+ last_hidden = hidden_states[pooling_metadata.get_pooling_cursor().last_token_indices_gpu].float()# Read per call: the weights load after construction, and the tied lm_head shares the embedding tensor.letter_weights = self.lm_head.weight[self.letter_token_ids].float()- return [None if row is None else letter_weights @ row[-1].float() for row in rows]+ return last_hidden @ letter_weights.T@default_pooling_type(seq_pooling_type="LAST", tok_pooling_type="ALL")diff --git a/products/ml_inference/packages/kev-vllm/kev_vllm/pending.py b/products/ml_inference/packages/kev-vllm/kev_vllm/pending.pynew file mode 100644index 000000000000..16d428db9db2--- /dev/null+++ b/products/ml_inference/packages/kev-vllm/kev_vllm/pending.py@@ -0,0 +1,58 @@+import threading+import time+from collections import deque+from collections.abc import Callable+from dataclasses import dataclass++# vLLM has no abort hook for IO processors, so entries of requests rejected or dropped after pre_process expire instead.+PENDING_MAX_AGE_SECONDS = 300+++@dataclass(frozen=False)+class _Entry[T]:+ request_id: str | None+ value: T+ created: float+ taken: bool = False+++class PendingRequests[T]:+ """What pre_process knew about a request, kept until post_process; vLLM calls both with the same request id and+ may run them on executor threads, so every access is serialised."""++ def __init__(self, max_age_seconds: float = PENDING_MAX_AGE_SECONDS, clock: Callable[[], float] = time.monotonic) -> None:+ self._by_id: dict[str | None, deque[_Entry[T]]] = {}+ self._by_age: deque[_Entry[T]] = deque()+ self._lock = threading.Lock()+ self._max_age_seconds = max_age_seconds+ self._clock = clock++ def put(self, request_id: str | None, value: T) -> None:+ with self._lock:+ now = self._clock()+ self._expire_older_than(now - self._max_age_seconds)+ entry = _Entry(request_id, value, now)+ self._by_id.setdefault(request_id, deque()).append(entry)+ self._by_age.append(entry)++ def take(self, request_id: str | None) -> T:+ with self._lock:+ self._expire_older_than(self._clock() - self._max_age_seconds)+ entries = self._by_id.get(request_id)+ if not entries:+ raise ValueError(f"request {request_id} waited longer than {self._max_age_seconds}s and expired")+ entry = entries.popleft()+ if not entries:+ del self._by_id[request_id]+ entry.taken = True+ return entry.value++ def _expire_older_than(self, cutoff: float) -> None:+ while self._by_age and (self._by_age[0].taken or self._by_age[0].created < cutoff):+ entry = self._by_age.popleft()+ if entry.taken:+ continue+ entries = self._by_id[entry.request_id]+ entries.popleft()+ if not entries:+ del self._by_id[entry.request_id]diff --git a/products/ml_inference/packages/kev-vllm/tests/test_pending.py b/products/ml_inference/packages/kev-vllm/tests/test_pending.pynew file mode 100644index 000000000000..330e2aed63c1--- /dev/null+++ b/products/ml_inference/packages/kev-vllm/tests/test_pending.py@@ -0,0 +1,34 @@+import pytest++from kev_vllm.pending import PendingRequests+++class Clock:+ def __init__(self) -> None:+ self.now = 0.0++ def __call__(self) -> float:+ return self.now+++def test_an_entry_nobody_takes_expires_when_a_later_request_arrives() -> None:+ clock = Clock()+ pending = PendingRequests[str](max_age_seconds=300, clock=clock)+ pending.put("rejected-with-503", "left behind")+ clock.now = 301.0+ pending.put("served", "answer")+ with pytest.raises(ValueError, match="expired"):+ pending.take("rejected-with-503")+ assert pending.take("served") == "answer"+++def test_a_reused_id_never_hands_out_an_expired_entry() -> None:+ clock = Clock()+ pending = PendingRequests[str](max_age_seconds=300, clock=clock)+ pending.put("a", "stale")+ clock.now = 299.0+ pending.put("a", "fresh")+ clock.now = 302.0+ assert pending.take("a") == "fresh"+ with pytest.raises(ValueError, match="expired"):+ pending.take("a")