Skip to content

: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.

fix(ml_inference): verify weights once, fail on any child exit, keep compile caches on the volume (#106211)

Robbiecd1904083552
diff --git a/products/ml_inference/packages/kev-vllm/Dockerfile b/products/ml_inference/packages/kev-vllm/Dockerfile
index 51722c4d8d68..6245ba4bc7d5 100644
--- a/products/ml_inference/packages/kev-vllm/Dockerfile
+++ b/products/ml_inference/packages/kev-vllm/Dockerfile
@@ -29,10 +29,11 @@ RUN pip install --no-cache-dir --no-deps . \
COPY bin/serve.sh /usr/local/bin/kev-vllm-serve
COPY serving/Caddyfile /etc/kev-vllm/Caddyfile
-# vLLM writes its compile and tokenizer caches under HOME, so the serving user needs one it owns. MODEL_DIR is owned by
-# the same user, so a named volume mounted there starts writable and keeps the weights across container restarts.
+# vLLM writes its tokenizer cache under HOME, so the serving user needs one it owns. MODEL_DIR and the compile caches
+# (bin/serve.sh) are owned by the same user, so a new named volume on /models starts writable and keeps both across
+# containers.
RUN useradd --system --uid 10001 --create-home --home-dir /home/kev --shell /usr/sbin/nologin kev \
- && install -d -o kev -g kev /models/model
+ && install -d -o kev -g kev /models/model /models/cache
USER kev
ENV HOME=/home/kev
diff --git a/products/ml_inference/packages/kev-vllm/README.md b/products/ml_inference/packages/kev-vllm/README.md
index 474994ad9122..7e2eef7f1355 100644
--- a/products/ml_inference/packages/kev-vllm/README.md
+++ b/products/ml_inference/packages/kev-vllm/README.md
@@ -84,7 +84,7 @@ Without a limit, overload makes the wait longer than the timeout, and the box an
`Dockerfile` builds the serving image, which is the whole serving box: the official `vllm/vllm-openai:v0.29.0` image with this package installed on top, Caddy for the bearer check, and s5cmd to fetch the weights. `.github/workflows/cd-ml-inference-decision-image.yml` builds it for amd64 on every master push that touches the package and publishes it as `posthog-ml-inference-decision` to ECR and GHCR; add the `build-ml-inference-image` label to a PR to build it early and push it to GHCR alone, tagged `pr-<number>`.
-The entrypoint (`bin/serve.sh`) fetches the checkpoint from `MODEL_URI` into `MODEL_DIR` unless one already matches its manifest there, checks it, runs `vllm serve` on loopback, and runs Caddy on `PORT` in front of it. Caddy answers 401 without `Authorization: Bearer $DECISION_BEARER` and exposes only `/pooling`, `/health` and `/metrics`. If either process exits, the container exits, so a host runs it under a restart policy:
+The entrypoint (`bin/serve.sh`) fetches the checkpoint from `MODEL_URI` into `MODEL_DIR` unless one already matches its manifest there, checks it, runs `vllm serve` on loopback, and runs Caddy on `PORT` in front of it. Caddy answers 401 without `Authorization: Bearer $DECISION_BEARER` and exposes only `/pooling`, `/health` and `/metrics`. If either process exits, the container exits with a failure status, even when the process itself exited cleanly, so a host runs it under a restart policy (`always` or `on-failure`):
```bash
docker run -d --restart always --gpus all --network host --shm-size 8g \
@@ -95,7 +95,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.
+- The named volume keeps the weights and the compile caches (`/models/cache`, or `CACHE_DIR`) across containers, so only the first container on a host pays the full compile. Docker creates the volume owned by the serving user (uid 10001). A host directory, or a volume created by an image without the cache directory, must be writable by that user. If the cache directory is not writable, the entrypoint says so and keeps the caches in the container.
- `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.
@@ -128,6 +128,18 @@ Measured 2026-09-22 on a Lambda 2x H100 SXM instance (one GPU used), vLLM 0.29.0
MLHog's `models/kev/load_generator.py` produced the throughput row: a closed loop of N workers over the parity records.
+### JevK5
+
+Measured 2026-09-24 on an L4 (EC2 g6.xlarge), vLLM 0.29.0, JevK5 at revision `27d2d6b8`: 294 questions, being JevBench's public sets, 28 of its hard states cut to about 1,300 tokens, and 35 invented edge cases. The reference is JevK5's own runtime (`jevk5` 0.2.0, transformers 5.17) on the same GPU, with its bf16 backbone and the answer read out again in fp32.
+
+| Compared | Max probability difference | Median | Argmax flips |
+| ------------------------------------------------- | -------------------------- | ------ | --------------------------------------------- |
+| Runtime's fp32 readout vs this image (bf16) | 0.046 | 0.0025 | 1, where the top two were 0.019 apart |
+| Runtime's fp32 readout vs its own default readout | 0.059 | 0.0036 | 4, where the top two were 0.024 apart or less |
+| Runtime's default readout vs `--quantization fp8` | 0.41 | 0.014 | at least 5, one with the top two 0.08 apart |
+
+The image is as close to the runtime's fp32 readout as the runtime's own default output is, so it serves JevK5 within the model's rounding noise. fp8 answers about 30% faster, but it moves answers far past that noise, so the image serves bf16. One short question (about 190 tokens) takes 51 ms at the median when it is alone on the GPU. The throughput under load is in [Load test on an L4](#load-test-on-an-l4).
+
## Evals
The eval runner that scores a served model on labelled suites lives in the MLHog repository under `models/kev/`, next to the other model work.
diff --git a/products/ml_inference/packages/kev-vllm/bin/serve.sh b/products/ml_inference/packages/kev-vllm/bin/serve.sh
index 85d0ffccc55f..409176a4add7 100755
--- a/products/ml_inference/packages/kev-vllm/bin/serve.sh
+++ b/products/ml_inference/packages/kev-vllm/bin/serve.sh
@@ -12,6 +12,7 @@ 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:-}
+CACHE_DIR=${CACHE_DIR:-/models/cache}
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
@@ -31,25 +32,41 @@ if [ -z "$MAX_NUM_QUEUED_TOKENS" ]; then
esac
fi
-if ! kev-vllm-checkpoint verify "$MODEL_DIR" >/dev/null 2>&1; then
+# Bash as PID 1 does not pass `docker stop` on to its children. Bash runs the trap only once a foreground command ends,
+# so a stop during the weight check or fetch lands after it, and the guards below keep the servers from starting.
+stopping=0
+trap 'stopping=1; kill $(jobs -p) 2>/dev/null || true' TERM INT
+
+if kev-vllm-checkpoint verify "$MODEL_DIR" >/dev/null 2>&1; then
+ echo "checkpoint at $MODEL_DIR matches its manifest" >&2
+else
if [ -z "$MODEL_URI" ]; then
echo "no checkpoint matching its manifest at $MODEL_DIR, and no MODEL_URI to fetch one from" >&2
exit 1
fi
echo "fetching $MODEL_URI into $MODEL_DIR" >&2
s5cmd --log error cp "${MODEL_URI%/}/*" "$MODEL_DIR/"
+ kev-vllm-checkpoint verify "$MODEL_DIR"
+fi
+
+# Docker seeds only a new volume from the image, so a volume created by an older image may have no writable cache dir.
+if mkdir -p "$CACHE_DIR/vllm" "$CACHE_DIR/triton" 2>/dev/null && [ -w "$CACHE_DIR/vllm" ] && [ -w "$CACHE_DIR/triton" ]; then
+ export VLLM_CACHE_ROOT="${VLLM_CACHE_ROOT:-$CACHE_DIR/vllm}" TRITON_CACHE_DIR="${TRITON_CACHE_DIR:-$CACHE_DIR/triton}"
+else
+ echo "$CACHE_DIR is not writable, so the compile caches stay in the container and every new container compiles again" >&2
fi
-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 INT
+if [ "$stopping" = 1 ]; then exit 0; fi
vllm 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" \
--max-num-queued-tokens "$MAX_NUM_QUEUED_TOKENS" "$@" &
+if [ "$stopping" = 1 ]; then wait || true; exit 0; fi
caddy run --config /etc/kev-vllm/Caddyfile --adapter caddyfile &
status=0
wait -n || status=$?
+# vLLM and Caddy both exit 0 on SIGTERM, so a clean exit that docker stop did not ask for still has to read as a failure.
+if [ "$stopping" = 1 ]; then status=0; elif [ "$status" = 0 ]; then status=1; fi
kill $(jobs -p) 2>/dev/null || true
wait || true
exit "$status"
diff --git a/products/ml_inference/packages/kev-vllm/serving/Caddyfile b/products/ml_inference/packages/kev-vllm/serving/Caddyfile
index e6f7ec0c1a81..8de173ef74fd 100644
--- a/products/ml_inference/packages/kev-vllm/serving/Caddyfile
+++ b/products/ml_inference/packages/kev-vllm/serving/Caddyfile
@@ -2,6 +2,7 @@
{
auto_https off
admin off
+ persist_config off
}
:{$PORT} {
diff --git a/products/ml_inference/packages/kev-vllm/tests/test_serve_entrypoint.py b/products/ml_inference/packages/kev-vllm/tests/test_serve_entrypoint.py
new file mode 100644
index 000000000000..a119b0e02420
--- /dev/null
+++ b/products/ml_inference/packages/kev-vllm/tests/test_serve_entrypoint.py
@@ -0,0 +1,131 @@
+import os
+import shutil
+import signal
+import subprocess
+import time
+from pathlib import Path
+
+import pytest
+
+SERVE = Path(__file__).resolve().parent.parent / "bin" / "serve.sh"
+STUBS = {
+ "kev-vllm-checkpoint": (
+ 'echo verify >> "$CALLS"; [ -n "${SLOW_VERIFY:-}" ] && sleep 2; [ -f "$CALLS.fetched" ] || [ -n "${VALID:-}" ]'
+ ),
+ "s5cmd": 'echo fetch >> "$CALLS"; touch "$CALLS.fetched"',
+ "vllm": (
+ 'echo "$*" > "$CALLS.vllm-args"; echo "vllm ${VLLM_CACHE_ROOT:-unset}" >> "$CALLS"\n'
+ '[ "${VLLM_EXITS:-}" = 1 ] && exit 0; exec sleep 30'
+ ),
+ "python3": '[ -n "${GPU:-}" ] && echo "$GPU"',
+ "caddy": (
+ 'if [ "${CADDY_EXITS:-}" = 1 ]; then until grep -q "^vllm " "$CALLS" 2>/dev/null; do sleep 0.01; done; exit 0; fi\nexec sleep 30'
+ ),
+}
+
+
+def bash_with_wait_n() -> str | None:
+ bash = shutil.which("bash")
+ check = "(( BASH_VERSINFO[0] > 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] >= 3) ))"
+ if bash is None or subprocess.run([bash, "-c", check]).returncode != 0:
+ return None
+ return bash
+
+
[email protected](scope="module")
+def bash() -> str:
+ found = bash_with_wait_n()
+ if found is None:
+ pytest.skip("the entrypoint needs bash 4.3 or later for wait -n")
+ return found
+
+
+def environment(tmp_path: Path, **overrides: str) -> dict[str, str]:
+ stubs = tmp_path / "bin"
+ stubs.mkdir()
+ for name, body in STUBS.items():
+ (stubs / name).write_text(f"#!/usr/bin/env bash\n{body}\n")
+ (stubs / name).chmod(0o755)
+ return {
+ "PATH": f"{stubs}:{os.environ['PATH']}",
+ "CALLS": str(tmp_path / "calls"),
+ "DECISION_BEARER": "test-bearer",
+ "CACHE_DIR": str(tmp_path / "cache"),
+ "GPU": "NVIDIA L4",
+ **overrides,
+ }
+
+
+def calls(tmp_path: Path) -> list[str]:
+ return (tmp_path / "calls").read_text().splitlines()
+
+
+ "overrides,expected_calls",
+ [
+ ({"VALID": "1", "VLLM_EXITS": "1"}, ["verify", "vllm {cache}/vllm"]),
+ ({"VALID": "1", "CADDY_EXITS": "1"}, ["verify", "vllm {cache}/vllm"]),
+ ({"MODEL_URI": "s3://bucket/model/", "VLLM_EXITS": "1"}, ["verify", "fetch", "verify", "vllm {cache}/vllm"]),
+ ({"VALID": "1", "VLLM_EXITS": "1", "VLLM_CACHE_ROOT": "/explicit"}, ["verify", "vllm /explicit"]),
+ ],
+)
+def test_a_child_that_exits_cleanly_on_its_own_fails_the_container(
+ bash: str, tmp_path: Path, overrides: dict[str, str], expected_calls: list[str]
+) -> None:
+ env = environment(tmp_path, **overrides)
+ result = subprocess.run([bash, SERVE], env=env, capture_output=True, text=True, timeout=30)
+ assert result.returncode == 1
+ assert calls(tmp_path) == [c.format(cache=env["CACHE_DIR"]) for c in expected_calls]
+
+
+ "overrides,expected_limit",
+ [
+ ({"GPU": "NVIDIA L4"}, "24000"),
+ ({"GPU": "Tesla T4"}, "5000"),
+ ({"GPU": "NVIDIA H100 80GB HBM3", "MAX_NUM_QUEUED_TOKENS": "276000"}, "276000"),
+ ({"GPU": "NVIDIA H100 80GB HBM3"}, None),
+ ({"GPU": ""}, None),
+ ],
+)
+def test_the_queue_limit_follows_the_gpu_or_refuses_to_guess(
+ bash: str, tmp_path: Path, overrides: dict[str, str], expected_limit: str | None
+) -> None:
+ env = environment(tmp_path, VALID="1", VLLM_EXITS="1", **overrides)
+ result = subprocess.run([bash, SERVE], env=env, capture_output=True, text=True, timeout=30)
+ if expected_limit is None:
+ assert result.returncode == 1
+ assert "no measured queue limit" in result.stderr
+ assert not (tmp_path / "calls.vllm-args").exists()
+ return
+ args = (tmp_path / "calls.vllm-args").read_text().split()
+ assert args[args.index("--max-num-queued-tokens") + 1] == expected_limit
+
+
+def test_a_stop_signal_exits_cleanly(bash: str, tmp_path: Path) -> None:
+ process = subprocess.Popen([bash, SERVE], env=environment(tmp_path, VALID="1"))
+ deadline = time.monotonic() + 20
+ while not (tmp_path / "calls").exists() or "vllm" not in (tmp_path / "calls").read_text():
+ assert time.monotonic() < deadline
+ time.sleep(0.05)
+ process.send_signal(signal.SIGTERM)
+ assert process.wait(timeout=10) == 0
+
+
+def test_a_stop_during_the_weight_check_starts_no_server(bash: str, tmp_path: Path) -> None:
+ process = subprocess.Popen([bash, SERVE], env=environment(tmp_path, VALID="1", SLOW_VERIFY="1"))
+ deadline = time.monotonic() + 20
+ while not (tmp_path / "calls").exists():
+ assert time.monotonic() < deadline
+ time.sleep(0.05)
+ process.send_signal(signal.SIGTERM)
+ assert process.wait(timeout=10) == 0
+ assert calls(tmp_path) == ["verify"]
+
+
+def test_an_unwritable_cache_dir_keeps_the_caches_in_the_container(bash: str, tmp_path: Path) -> None:
+ (tmp_path / "not-a-dir").write_text("")
+ env = environment(tmp_path, VALID="1", VLLM_EXITS="1", CACHE_DIR=str(tmp_path / "not-a-dir" / "cache"))
+ result = subprocess.run([bash, SERVE], env=env, capture_output=True, text=True, timeout=30)
+ assert "not writable" in result.stderr
+ assert calls(tmp_path)[-1] == "vllm unset"