: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): serve JevK5 from a self-contained serving image (#104145)
Robbie3968800d25b4
diff --git a/.github/workflows/cd-ml-inference-decision-image.yml b/.github/workflows/cd-ml-inference-decision-image.ymlnew file mode 100644index 000000000000..3b1fa11ea257--- /dev/null+++ b/.github/workflows/cd-ml-inference-decision-image.yml@@ -0,0 +1,90 @@+#+# Build and push the decision model serving image: the official vLLM image plus the kev-vllm plugin package, Caddy and+# s5cmd. Weights are not in the image; the entrypoint fetches them (see the package README).+#+name: ML Inference Decision Image CD++on:+ push:+ branches:+ - master+ paths:+ - 'products/ml_inference/packages/kev-vllm/**'+ - '.github/workflows/cd-ml-inference-decision-image.yml'+ # Adding the build-ml-inference-image label builds the PR's head at that moment and pushes it to GHCR alone, so a GPU+ # host can pull it for a trial before the change lands. A later push does not rebuild until someone adds the label+ # again, which ties each build to a commit a person chose, as container-images-label-ci.yml does.+ pull_request:+ types: [labeled]+ paths:+ - 'products/ml_inference/packages/kev-vllm/**'+ - '.github/workflows/cd-ml-inference-decision-image.yml'+ workflow_dispatch:++concurrency:+ # An unrelated label must not cancel a build already in progress.+ group: >-+ ${{ github.workflow }}-${{+ github.event_name == 'push' && github.sha+ || github.event_name == 'pull_request' && github.event.label.name != 'build-ml-inference-image'+ && format('ignored-label-{0}', github.event.label.name)+ || github.head_ref || github.ref+ }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++jobs:+ build:+ name: Build and push decision serving image+ if: |+ github.repository_owner == 'PostHog' && (+ github.event_name == 'push' ||+ github.event_name == 'workflow_dispatch' ||+ (github.event.pull_request.head.repo.full_name == github.repository &&+ github.event.label.name == 'build-ml-inference-image')+ )+ runs-on: depot-ubuntu-24.04+ timeout-minutes: 30+ permissions:+ id-token: write+ contents: read+ packages: write++ outputs:+ digest: ${{ steps.build.outputs.digest }}++ steps:+ - name: Check out+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ fetch-depth: 2++ - name: Set up Depot CLI+ uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1++ - name: Docker meta and registry login+ id: docker-meta+ uses: ./.github/actions/docker-meta+ with:+ image-name: posthog-ml-inference-decision+ aws-role-to-assume: ${{ vars.AWS_ECR_POSTHOG_MASTER_PUBLISH_IAM_ROLE }}+ push-to-ecr: ${{ github.ref == 'refs/heads/master' }}+ github-token: ${{ secrets.GITHUB_TOKEN }}+ dockerhub-username: ${{ secrets.DOCKERHUB_USER }}+ dockerhub-password: ${{ secrets.DOCKERHUB_TOKEN }}+ push-to-dockerhub: 'false'+ push-to-ghcr: ${{ vars.PUBLIC_IMAGE_PUSH_PAUSED != 'true' }}++ - name: Build and push container image+ id: build+ uses: depot/build-push-action@5f3b3c2e5a00f0093de47f657aeaefcedff27d18 # v1.17.0+ with:+ project: c1f2m5s6zd+ context: ./products/ml_inference/packages/kev-vllm+ file: ./products/ml_inference/packages/kev-vllm/Dockerfile+ buildx-fallback: false+ # The GPU hosts are x86; the base image has no CUDA build for arm64 worth paying for.+ platforms: linux/amd64+ push: ${{ github.event_name == 'pull_request' || vars.CD_DEPLOY_ENABLED == 'true' }}+ tags: ${{ steps.docker-meta.outputs.tags }}+ labels: ${{ steps.docker-meta.outputs.labels }}+ annotations: ${{ steps.docker-meta.outputs.annotations }}diff --git a/products/ml_inference/packages/kev-vllm/.dockerignore b/products/ml_inference/packages/kev-vllm/.dockerignorenew file mode 100644index 000000000000..e5cb8a307a7e--- /dev/null+++ b/products/ml_inference/packages/kev-vllm/.dockerignore@@ -0,0 +1,9 @@+.venv*/+build/+tests/+bin/+!bin/serve.sh+__pycache__/+*.egg-info/+README.md+uv.lockdiff --git a/products/ml_inference/packages/kev-vllm/Dockerfile b/products/ml_inference/packages/kev-vllm/Dockerfilenew file mode 100644index 000000000000..51722c4d8d68--- /dev/null+++ b/products/ml_inference/packages/kev-vllm/Dockerfile@@ -0,0 +1,43 @@+# The serving image for PostHog's decision models: the official vLLM image plus this package, which registers the model+# classes and the /v1/systemone IO processors through its entry points, plus Caddy for the bearer check and s5cmd to+# fetch the weights. Weights are not in the image; bin/serve.sh fetches them from MODEL_URI into MODEL_DIR.+FROM vllm/vllm-openai:v0.29.0@sha256:c2914767605584b6d8f45686b82de173ecc99e781897aa3d0a66dacd72c51ae1++# vLLM 0.29's V2 model runner does not run the plugin pooling task that IO processors use; the V1 runner does.+# One GPU per box means Gloo only talks to itself, and binding it to loopback avoids resolving the host name, which+# fails at the kernel's 64-character limit in VPCs with a long DHCP domain.+ENV VLLM_USE_V2_MODEL_RUNNER=0 \+ GLOO_SOCKET_IFNAME=lo \+ MODEL_DIR=/models/model \+ MODEL_NAME=jevk5-0.2 \+ PORT=8000++COPY --from=caddy:2.10.2@sha256:c3d7ee5d2b11f9dc54f947f68a734c84e9c9666c92c88a7f30b9cba5da182adb /usr/bin/caddy /usr/local/bin/caddy+ARG S5CMD_VERSION=2.3.0+ARG S5CMD_SHA256=de0fdbfa3aceae55e069ba81a0fc17b2026567637603734a387b2fca06c299b4+RUN curl -sSfL "https://github.com/peak/s5cmd/releases/download/v${S5CMD_VERSION}/s5cmd_${S5CMD_VERSION}_Linux-64bit.tar.gz" -o /tmp/s5cmd.tar.gz \+ && echo "${S5CMD_SHA256} /tmp/s5cmd.tar.gz" | sha256sum -c - \+ && tar --no-same-owner -xzf /tmp/s5cmd.tar.gz -C /usr/local/bin s5cmd \+ && rm /tmp/s5cmd.tar.gz++WORKDIR /opt/kev-vllm+COPY pyproject.toml ./+COPY kev_vllm ./kev_vllm+# --no-deps keeps the image's torch, transformers and pydantic; the package's own pins are for the export environment.+RUN pip install --no-cache-dir --no-deps . \+ && python3 -c "import kev_vllm.plugin, kev_vllm.checkpoint, kev_vllm.jevk5_io_processor"+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.+RUN useradd --system --uid 10001 --create-home --home-dir /home/kev --shell /usr/sbin/nologin kev \+ && install -d -o kev -g kev /models/model+USER kev+ENV HOME=/home/kev++EXPOSE 8000+# vLLM's own health on loopback: Caddy's /health needs the bearer. Start-up covers a weight fetch and graph capture.+HEALTHCHECK --interval=30s --timeout=5s --start-period=900s --retries=3 \+ CMD curl -fs "http://127.0.0.1:${VLLM_PORT:-8001}/health" || exit 1+ENTRYPOINT ["kev-vllm-serve"]diff --git a/products/ml_inference/packages/kev-vllm/README.md b/products/ml_inference/packages/kev-vllm/README.mdindex f5d51eb81535..206600d4bd26 100644--- a/products/ml_inference/packages/kev-vllm/README.md+++ b/products/ml_inference/packages/kev-vllm/README.md@@ -1,44 +1,69 @@# kev-vllm-Serves [Kev](https://github.com/jaredpalmer/kev) decision models on vLLM. Kev is Qwen3.5 plus a LoRA and a pointer head: one `state`, several typed questions, a calibrated probability per question, no generated text. The design behind this package is the ML inference RFC in the internal requests-for-comments repo (PR 1277).+Serves PostHog's decision models on vLLM: one `state`, several typed questions, a calibrated probability per question, no generated text. The model in production is [JevK5](https://github.com/allebee/jevk5) v0.2, Qwen3.5-4B with a merged LoRA that reads each answer from the answer letters' next-token logits. The package started with [Kev](https://github.com/jaredpalmer/kev), Qwen3.5 plus a LoRA and a pointer head, and still serves it. A checkpoint's `config.json` picks the model class (`architectures`) and the IO processor (`io_processor_plugin`).-Three parts:+- `kev_vllm.jevk5`, `kev_vllm.jevk5_model`, `kev_vllm.jevk5_io_processor`: JevK5's prompt and readout, ported from its runtime; `JevK5ForDecision`, a pooling model that returns the letter logits at the last token; and the IO processor that turns a TypeSafe `/v1/systemone` request into one prompt per question and the logits back into answers.+- `kev_vllm.model`, `kev_vllm.io_processor`: `KevForDecision` and Kev's IO processor, which encodes a request exactly as Kev does (one causal row per question) and applies the pointer head.+- `kev_vllm.jevk5_export`, `kev_vllm.export`, `kev_vllm.checkpoint`, `kev_vllm.parity`: turn a Hub checkpoint into a directory the image serves, verify one against its manifest, and check a Kev export against Kev's own path on this machine.-- `kev_vllm.model`: `KevForDecision`, a vLLM pooling model on the stock Qwen3.5 class. Its pooler reads the option-end and decide token hidden states of each row and applies the head, so vLLM batches rows across requests.-- `kev_vllm.io_processor`: a vLLM IO-processor plugin that accepts a TypeSafe `/v1/systemone` request on the `/pooling` endpoint, encodes it exactly as Kev does (one causal row per question), and returns Kev's answer shape plus `probabilities_raw`.-- `kev_vllm.export`, `kev_vllm.checkpoint`, `kev_vllm.parity`: turn a Kev checkpoint into a vLLM-loadable directory, verify one against its manifest, and check an export against Kev's own path on this machine.--Publishing a version, measuring parity against a served model, load testing and the evals live in the MLHog repo under `models/kev`. This package downloads weights and runs inference; it never writes to a bucket.+Both IO processors return the same answer shape, so the AI gateway and Django see one contract. Publishing a version, measuring parity against a served model, load testing and the evals live in the MLHog repo under `models/kev`. This package downloads weights and runs inference; it never writes to a bucket.`kev_vllm/kev_compat.py` is vendored from Kev (Apache-2.0) because the `kev` package pins a torch version vLLM cannot use.## Export a checkpoint+```bash+uv run jevk5-vllm-export --revision 27d2d6b8d4714807f6293b0623bd7370b27e42f8 --out build/jevk5-4b+```++Downloads JevK5 at a pinned Hub commit, checks every LFS file against the sha256 the Hub records, adds the `jevk5_*` fields and the model class to `config.json`, and writes `manifest.json`. The weights are copied unchanged in bf16; a GPU without bf16, such as a T4, casts them to fp16 at load (`DTYPE=float16`). It needs no GPU and no extra.+```bashuv run --extra export kev-vllm-export --run jaredpalmer/kev-4b --out build/kev-4b```-Downloads the base model and adapter, merges the LoRA in fp32 the way `kev.serve` does, casts to bf16, and writes `config.json`, `model.safetensors`, the tokenizer, and `manifest.json` with every hash. About 16 GB of RAM and 20 GB of disk.+For Kev, `kev-vllm-export` downloads the base model and adapter, merges the LoRA in fp32 the way `kev.serve` does, casts to bf16, and writes `config.json`, `model.safetensors`, the tokenizer, and `manifest.json` with every hash. About 16 GB of RAM and 20 GB of disk.## Serve-On a CUDA box with the `serve` extra installed (`uv sync --extra serve`), the entry points register the model class and the IO processor on import:+On a CUDA box with the `serve` extra installed (`uv sync --extra serve`), the entry points register the model classes and the IO processors on import:```bash-VLLM_USE_V2_MODEL_RUNNER=0 vllm serve /models/kev-4b --served-model-name kev-4b --mamba-ssm-cache-dtype float32 --port 8000+VLLM_USE_V2_MODEL_RUNNER=0 vllm serve build/jevk5-4b --served-model-name jevk5-0.2 --mamba-ssm-cache-dtype float32 --port 8000````VLLM_USE_V2_MODEL_RUNNER=0` is required on vLLM 0.29: its new model runner does not run the `plugin` pooling task that IO processors use.-`config.json` names the IO processor (`io_processor_plugin: "kev"`), so no extra flag is needed. Then:+`config.json` names the IO processor (`io_processor_plugin: "jevk5"`, or `"kev"` for Kev), so no extra flag is needed. Then:```bash-curl -s localhost:8000/pooling -H 'content-type: application/json' -d '{"model": "kev-4b", "data": {"state": "It has been two weeks and the refund has not arrived.", "questions": {"refund": {"type": "noul", "instructions": "Is the customer asking about a refund?"}}}}'+curl -s localhost:8000/pooling -H 'content-type: application/json' -d '{"model": "jevk5-0.2", "data": {"state": "It has been two weeks and the refund has not arrived.", "questions": {"refund": {"type": "noul", "instructions": "Is the customer asking about a refund?"}}}}'```-The answer is under `data.answers`, in Kev's format, with `data.probabilities_raw` alongside for parity checks.+The answer is under `data.answers`, in Kev's format for either model, with `data.probabilities_raw` alongside for parity checks. JevK5 takes at most 16 options per question and 16,384 tokens per prompt, and refuses more.++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.++## Container image++`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>`.-Prefix caching is off for this model: vLLM does not enable it for pooling models on hybrid backbones, so every row recomputes its state. Batching across rows and requests still applies.+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:++```bash+docker run -d --restart always --gpus all --network host --shm-size 8g \+ -v ml-models:/models \+ -e MODEL_URI=s3://<base-models bucket>/posthog/jevk5-4b-vllm/<version>/ \+ -e DECISION_BEARER \+ ghcr.io/posthog/posthog-ml-inference-decision@sha256:<digest>+```++- 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`.+- 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.## Parity@@ -66,6 +91,10 @@ Measured 2026-09-22 on a Lambda 2x H100 SXM instance (one GPU used), vLLM 0.29.0MLHog's `models/kev/load_generator.py` produced the throughput row: a closed loop of N workers over the parity records.+## 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.+## Tests```bashdiff --git a/products/ml_inference/packages/kev-vllm/bin/serve.sh b/products/ml_inference/packages/kev-vllm/bin/serve.shnew file mode 100755index 000000000000..c4dc5494f515--- /dev/null+++ b/products/ml_inference/packages/kev-vllm/bin/serve.sh@@ -0,0 +1,38 @@+#!/usr/bin/env bash+# Container entrypoint and the whole serving box: fetch the checkpoint when MODEL_DIR does not already match its+# manifest, run vLLM on loopback, and put Caddy in front of it on PORT. Caddy rejects a request without the bearer and+# exposes only the decision endpoint, health and metrics. The container exits when either process does, so the host's+# restart policy brings both back. Extra arguments go to `vllm serve`.+set -euo pipefail++MODEL_DIR=${MODEL_DIR:-/models/model}+MODEL_URI=${MODEL_URI:-}+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}+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++if ! kev-vllm-checkpoint verify "$MODEL_DIR" >/dev/null 2>&1; then+ 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/"+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+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" "$@" &+caddy run --config /etc/kev-vllm/Caddyfile --adapter caddyfile &++status=0+wait -n || status=$?+kill $(jobs -p) 2>/dev/null || true+wait || true+exit "$status"diff --git a/products/ml_inference/packages/kev-vllm/deploy/phase1/envs/prod-us.env b/products/ml_inference/packages/kev-vllm/deploy/phase1/envs/prod-us.envdeleted file mode 100644index 479c9e90fe52..000000000000--- a/products/ml_inference/packages/kev-vllm/deploy/phase1/envs/prod-us.env+++ /dev/null@@ -1,15 +0,0 @@-LAMBDA_SSH_KEY="op://ML/Lambda Prod US/private key?ssh-format=openssh"-BASE_MODELS_BUCKET=posthog-ml-training-prod-us-east-1-base-models-AWS_READ_PROFILE=ml-prod-us-AWS_REGION=us-east-1-MODEL_NAME=kev-4b-MODEL_VERSION=485ace8703592fcf405488b262449990824cfed1-INSTANCE_HOST=kev-1.inference.posthog.dev-IMAGE=ghcr.io/posthog/posthog-ml-inference-decision:pr-104145-KEV_DATE_FACTS=0-ROUTE53_ZONE_ID=placeholder-AWS_ACCESS_KEY_ID=placeholder-AWS_SECRET_ACCESS_KEY=placeholder-KEV_BEARER=placeholderdiff --git a/products/ml_inference/packages/kev-vllm/kev_vllm/checkpoint.py b/products/ml_inference/packages/kev-vllm/kev_vllm/checkpoint.pynew file mode 100644index 000000000000..051517fcc430--- /dev/null+++ b/products/ml_inference/packages/kev-vllm/kev_vllm/checkpoint.py@@ -0,0 +1,80 @@+"""Verify an exported checkpoint directory against the hashes in its manifest.json.++ kev-vllm-checkpoint verify /models/kev-4b++Exit status 0 when every file the manifest lists is present with the recorded sha256, 1 otherwise.+"""++import argparse+import hashlib+import json+import sys+from pathlib import Path+from typing import Any, TypedDict+++class ManifestFile(TypedDict):+ sha256: str+ size_bytes: int+++class Manifest(TypedDict, total=False):+ """What kev-vllm-export and jevk5-vllm-export write; `files` is the part verification needs, the rest is provenance."""++ kev_run: str+ kev_hub_revision: str+ source_repo: str+ source_revision: str+ files: dict[str, ManifestFile]+++def sha256_of(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as f:+ for chunk in iter(lambda: f.read(1 << 20), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def read_manifest(checkpoint_dir: Path) -> Manifest:+ manifest_path = checkpoint_dir / "manifest.json"+ if not manifest_path.is_file():+ raise FileNotFoundError(f"{checkpoint_dir} has no manifest.json; it is not an exported checkpoint")+ manifest: Any = json.loads(manifest_path.read_text(encoding="utf-8"))+ if not isinstance(manifest, dict) or not isinstance(manifest.get("files"), dict):+ raise ValueError(f"{manifest_path} has no files table; it is not a manifest kev-vllm-export wrote")+ return manifest+++def verify(checkpoint_dir: Path) -> Manifest:+ manifest = read_manifest(checkpoint_dir)+ problems = []+ for name, meta in manifest["files"].items():+ path = checkpoint_dir / name+ if not path.is_file():+ problems.append(f"{name}: missing")+ elif sha256_of(path) != meta["sha256"]:+ problems.append(f"{name}: sha256 mismatch")+ if problems:+ raise ValueError("checkpoint does not match its manifest: " + ", ".join(problems))+ return manifest+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ sub = parser.add_subparsers(dest="command", required=True)+ ver = sub.add_parser("verify")+ ver.add_argument("checkpoint_dir", type=Path)+ args = parser.parse_args()+ try:+ manifest = verify(args.checkpoint_dir)+ except (FileNotFoundError, ValueError) as error:+ print(error, file=sys.stderr)+ raise SystemExit(1) from error+ source = manifest.get("kev_run") or manifest.get("source_repo")+ revision = manifest.get("kev_hub_revision") or manifest.get("source_revision")+ print(f"checkpoint ok: {source} @ {revision}, {len(manifest['files'])} files")+++if __name__ == "__main__":+ main()diff --git a/products/ml_inference/packages/kev-vllm/kev_vllm/export.py b/products/ml_inference/packages/kev-vllm/kev_vllm/export.pyindex 38321d3338b8..7d72e4a8e12a 100644--- a/products/ml_inference/packages/kev-vllm/kev_vllm/export.py+++ b/products/ml_inference/packages/kev-vllm/kev_vllm/export.py@@ -15,7 +15,6 @@ Needs the `export` extra (the `kev` package and its pinned torch), so run it in"""import argparse-import hashlibimport jsonfrom datetime import UTC, datetimefrom pathlib import Path@@ -23,6 +22,7 @@ from pathlib import Pathimport torchfrom kev_vllm import __version__+from kev_vllm.checkpoint import sha256_offrom kev_vllm.kev_compat import KEV_SOURCE_COMMIT, SPECIALARCHITECTURE = "KevForDecision"@@ -30,14 +30,6 @@ IO_PROCESSOR_PLUGIN = "kev"DTYPES = {"bf16": torch.bfloat16, "fp32": torch.float32}-def sha256_of(path: Path) -> str:- digest = hashlib.sha256()- with path.open("rb") as f:- for chunk in iter(lambda: f.read(1 << 20), b""):- digest.update(chunk)- return digest.hexdigest()--def hub_revision(resolved_path: str) -> str | None:"""The commit a Hub snapshot was downloaded at: `.../snapshots/<sha>` in the HF cache. None for a local run."""path = Path(resolved_path)diff --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 5000c07ef3ac..249505db334f 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@@ -26,17 +26,40 @@ INFER_MAX_STATE, INFER_MAX_BRANCH = 8192, 8192PENDING_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 value++class KevIOProcessor(IOProcessor[SystemOneRequest, dict]):def __init__(self, vllm_config: VllmConfig, renderer: BaseRenderer) -> None:super().__init__(vllm_config, renderer)model_config = vllm_config.model_configself.tokenizer = AutoTokenizer.from_pretrained(model_config.tokenizer, revision=model_config.tokenizer_revision)self.served_model = model_config.served_model_name- # request_id -> (question metadata, input token count, enqueued at); vLLM calls pre_process and post_process- # with the same id- self._pending: dict[str | None, deque[tuple[list[dict], int, float]]] = {}- # vLLM may run pre_process and post_process on executor threads, so every access to the map is serialised.- self._pending_lock = threading.Lock()+ self._pending: PendingRequests[tuple[list[dict], int]] = PendingRequests()def parse_data(self, data: object) -> SystemOneRequest:return SystemOneRequest.model_validate(data)@@ -45,20 +68,11 @@ class KevIOProcessor(IOProcessor[SystemOneRequest, dict]):record, meta = to_record(prompt)enc = encode(self.tokenizer, record, max_state=INFER_MAX_STATE, max_branch=INFER_MAX_BRANCH)state_ids, _, rows = rows_of(enc)- with self._pending_lock:- if len(self._pending) > PENDING_SWEEP_SIZE:- self._sweep_pending()- self._pending.setdefault(request_id, deque()).append((meta, len(enc["ids"]), time.monotonic()))+ self._pending.put(request_id, (meta, len(enc["ids"])))return [TokensPrompt(prompt_token_ids=state_ids + row["ids"]) for row in rows]def post_process(self, model_output: Sequence[PoolingRequestOutput], request_id: str | None = None, **kwargs) -> dict:- with self._pending_lock:- entries = self._pending.get(request_id)- if not entries:- raise ValueError(f"request {request_id} waited longer than {PENDING_MAX_AGE_SECONDS}s and was swept")- meta, input_tokens, _ = entries.popleft()- if not entries:- del self._pending[request_id]+ meta, input_tokens = self._pending.take(request_id)probs = [out.outputs.data.tolist() for out in model_output]if len(probs) != len(meta):raise ValueError(f"got {len(probs)} rows back for {len(meta)} questions")@@ -69,9 +83,3 @@ class KevIOProcessor(IOProcessor[SystemOneRequest, dict]):"probabilities_raw": probs,"usage": {"input_tokens": input_tokens, "output_tokens": output_tokens(self.tokenizer, answers)},}-- def _sweep_pending(self) -> None:- """Caller holds the lock."""- cutoff = time.monotonic() - PENDING_MAX_AGE_SECONDS- for request_id in [rid for rid, entries in self._pending.items() if entries[0][2] < cutoff]:- del self._pending[request_id]diff --git a/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5.py b/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5.pynew file mode 100644index 000000000000..22fa5b84581c--- /dev/null+++ b/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5.py@@ -0,0 +1,84 @@+"""JevK5's prompt and readout, ported from its runtime (github.com/allebee/jevk5, jevk5/runtime.py at v0.2.0).++JevK5 is Qwen3.5-4B with a merged LoRA. It answers one question per causal row: a fixed system instruction, the+decision as JSON (evidence, criterion, lettered options), the chat template with thinking off, then a softmax over the+answer letters' next-token logits divided by one calibration temperature. The prompt text must match the runtime byte+for byte, because the LoRA was trained on it.+"""++import json+import math+from collections.abc import Sequence+from dataclasses import dataclass++from kev_vllm.kev_compat import JSONContent, Noul, Question, Score++LETTERS = "ABCDEFGHIJKLMNOP"+MAX_OPTIONS = len(LETTERS)+# The runtime refuses longer inputs rather than cutting them.+MAX_INPUT_TOKENS = 16_384+SYSTEM = (+ "Apply the supplied criterion to the supplied evidence. Choose exactly one listed option. "+ "Respond with only its uppercase letter, with no explanation or reasoning."+)+++@dataclass(frozen=True, kw_only=True, slots=True)+class Option:+ key: str+ text: str+++def options(question: Question) -> list[Option]:+ """Options in the order the letters are assigned: noul is true then false, choice follows its criteria, score is the+ levels lowest first."""+ if isinstance(question, Noul):+ criteria = question.criteria or {}+ pairs = [(key, criteria.get(key) or f"The proposition is {key}.") for key in ("true", "false")]+ elif isinstance(question, Score):+ pairs = [(str(level), description) for level, description in enumerate(question.criteria)]+ else:+ pairs = [(key, description or key) for key, description in question.criteria.items()]+ return [Option(key=key, text=f"{key}: {description}") for key, description in pairs]+++def messages(state: JSONContent, question: Question) -> list[dict[str, str]]:+ texts = [option.text for option in options(question)]+ if len(texts) > MAX_OPTIONS:+ raise ValueError(f"JevK5 answers at most {MAX_OPTIONS} options per question, got {len(texts)}")+ payload = {+ "evidence": state,+ "criterion": question.instructions,+ "options": [{"letter": LETTERS[i], "description": text} for i, text in enumerate(texts)],+ }+ return [+ {"role": "system", "content": SYSTEM},+ {"role": "user", "content": json.dumps(payload, ensure_ascii=False)},+ ]+++def prompt_ids(tokenizer, 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:+ raise ValueError(f"JevK5 answers inputs of at most {MAX_INPUT_TOKENS} tokens, this question has {len(ids)}")+ return ids+++def letter_token_ids(tokenizer) -> 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")+ return [letter_ids[0] for letter_ids in ids]+++def probabilities(letter_logits: Sequence[float], question: Question, temperature: float, keys: Sequence[str]) -> list[float]:+ """Calibrated probabilities reported in `keys` order (kev_compat.question_keys), which for noul is false then true,+ the reverse of the letter order."""+ by_letter = [option.key for option in options(question)]+ scaled = [logit / temperature for logit in letter_logits[: len(by_letter)]]+ top = max(scaled)+ weights = [math.exp(value - top) for value in scaled]+ total = sum(weights)+ by_key = {key: weight / total for key, weight in zip(by_letter, weights, strict=True)}+ return [by_key[key] for key in keys]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.pynew file mode 100644index 000000000000..e0fbec30a1f6--- /dev/null+++ b/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5_export.py@@ -0,0 +1,101 @@+"""Export JevK5 from the Hugging Face Hub as a directory the serving image loads.++ jevk5-vllm-export --revision 27d2d6b8d4714807f6293b0623bd7370b27e42f8 --out build/jevk5-4b++JevK5's weights are already a merged, text-only Qwen3.5 checkpoint, so they are copied unchanged. The export pins a+Hub commit, checks every LFS file against the sha256 the Hub records, and points config.json at this package's model+class and IO processor:++ config.json JevK5's config with architectures=["JevK5ForDecision"] and the jevk5_* fields+ model.safetensors JevK5's weights, unchanged (bf16; `--dtype float16` casts them at load on GPUs without bf16)+ tokenizer files as JevK5 ships them, including chat_template.jinja+ manifest.json source repo and revision, file hashes++Needs only the base dependencies, so it runs on a machine without a GPU.+"""++import argparse+import json+import re+import shutil+from datetime import UTC, datetime+from pathlib import Path++from huggingface_hub import HfApi, snapshot_download+from transformers import AutoTokenizer++from kev_vllm import __version__+from kev_vllm.checkpoint import sha256_of+from kev_vllm.jevk5 import letter_token_ids++SOURCE_REPO = "alibiserikbay/JevK5"+ARCHITECTURE = "JevK5ForDecision"+IO_PROCESSOR_PLUGIN = "jevk5"+FILES = [+ "config.json",+ "model.safetensors",+ "tokenizer.json",+ "tokenizer_config.json",+ "chat_template.jinja",+ "generation_config.json",+ "jevk5_config.json",+ "README.md",+]+++def export(repo: str, revision: str, out: Path) -> dict:+ 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)+ snapshot_download(repo, revision=revision, allow_patterns=FILES, local_dir=out)+ # The Hub client's download bookkeeping; an uploader copying the directory must not publish it.+ shutil.rmtree(out / ".cache", ignore_errors=True)++ info = HfApi().model_info(repo, revision=revision, files_metadata=True)+ for sibling in info.siblings or []:+ if sibling.rfilename in FILES and sibling.lfs is not None:+ if sha256_of(out / sibling.rfilename) != sibling.lfs.sha256:+ raise ValueError(f"{sibling.rfilename} does not match the sha256 the Hub records at {revision}")++ config = json.loads((out / "config.json").read_text())+ if config.get("architectures") != ["Qwen3_5ForCausalLM"]:+ raise ValueError(f"expected a text-only Qwen3.5 causal LM, got {config.get('architectures')}")+ temperature = json.loads((out / "jevk5_config.json").read_text())["temperature"]+ config.update(+ {+ "architectures": [ARCHITECTURE],+ "io_processor_plugin": IO_PROCESSOR_PLUGIN,+ "jevk5_temperature": float(temperature),+ "jevk5_letter_token_ids": letter_token_ids(AutoTokenizer.from_pretrained(out)),+ "jevk5_source": {"repo": repo, "revision": revision},+ }+ )+ (out / "config.json").write_text(json.dumps(config, indent=2, sort_keys=True) + "\n")++ manifest = {+ "model": "jevk5",+ "source_repo": repo,+ "source_revision": revision,+ "kev_vllm_version": __version__,+ "exported_at": datetime.now(UTC).isoformat(timespec="seconds"),+ "files": {},+ }+ for name in FILES:+ path = out / name+ manifest["files"][name] = {"sha256": sha256_of(path), "size_bytes": path.stat().st_size}+ (out / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")+ return manifest+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--repo", default=SOURCE_REPO)+ parser.add_argument("--revision", required=True, help="full Hub commit sha")+ parser.add_argument("--out", type=Path, required=True)+ args = parser.parse_args()+ manifest = export(args.repo, args.revision, args.out)+ print(json.dumps({k: v for k, v in manifest.items() if k != "files"}, indent=2))+++if __name__ == "__main__":+ main()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.pynew file mode 100644index 000000000000..1403dc2b9e1b--- /dev/null+++ b/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5_io_processor.py@@ -0,0 +1,54 @@+"""vLLM IO-processor plugin for JevK5: a TypeSafe `/v1/systemone` request in, answers in the same shape as Kev's out.++`pre_process` returns one prompt per question, each carrying the whole state, so vLLM batches the questions like any+other rows. `post_process` turns each row's letter logits into that question's probabilities.+"""++from collections.abc import Sequence++from transformers import AutoTokenizer+from vllm.config import VllmConfig+from vllm.inputs import TokensPrompt+from vllm.outputs import PoolingRequestOutput+from vllm.plugins.io_processors.interface import IOProcessor+from vllm.renderers import BaseRenderer++from kev_vllm import jevk5+from kev_vllm.io_processor import PendingRequests+from kev_vllm.kev_compat import Question, SystemOneRequest, output_tokens, to_answers, to_record+++class JevK5IOProcessor(IOProcessor[SystemOneRequest, dict]):+ def __init__(self, vllm_config: VllmConfig, renderer: BaseRenderer) -> None:+ super().__init__(vllm_config, renderer)+ model_config = vllm_config.model_config+ self.tokenizer = AutoTokenizer.from_pretrained(model_config.tokenizer, revision=model_config.tokenizer_revision)+ self.served_model = model_config.served_model_name+ self.temperature = float(model_config.hf_text_config.jevk5_temperature)+ self._pending: PendingRequests[tuple[list[Question], list[dict], int]] = PendingRequests()++ def parse_data(self, data: object) -> SystemOneRequest:+ return SystemOneRequest.model_validate(data)++ def pre_process(self, prompt: SystemOneRequest, request_id: str | None = None, **kwargs) -> Sequence[TokensPrompt]:+ questions = list(prompt.questions.values())+ rows = [jevk5.prompt_ids(self.tokenizer, prompt.state, question) for question in questions]+ _, meta = to_record(prompt)+ self._pending.put(request_id, (questions, meta, sum(len(row) for row in rows)))+ return [TokensPrompt(prompt_token_ids=row) for row in rows]++ def post_process(self, model_output: Sequence[PoolingRequestOutput], request_id: str | None = None, **kwargs) -> dict:+ questions, meta, input_tokens = self._pending.take(request_id)+ if len(model_output) != len(questions):+ raise ValueError(f"got {len(model_output)} rows back for {len(questions)} questions")+ probs = [+ jevk5.probabilities(out.outputs.data.tolist(), question, self.temperature, question_meta["keys"])+ for out, question, question_meta in zip(model_output, questions, meta, strict=True)+ ]+ answers = to_answers(probs, meta)+ return {+ "model": self.served_model,+ "answers": answers,+ "probabilities_raw": probs,+ "usage": {"input_tokens": input_tokens, "output_tokens": output_tokens(self.tokenizer, answers)},+ }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.pynew file mode 100644index 000000000000..2969a9ed9318--- /dev/null+++ b/products/ml_inference/packages/kev-vllm/kev_vllm/jevk5_model.py@@ -0,0 +1,49 @@+"""vLLM model class for JevK5: the Qwen3.5 causal LM, pooled to the answer letters' next-token logits.++Registered under the architecture name `JevK5ForDecision` by `kev_vllm.plugin.register`. The exported checkpoint+(`kev_vllm.jevk5_export`) is JevK5's own weights with `jevk5_letter_token_ids` and `jevk5_temperature` added to its+config. The pooler returns raw logits; the IO processor applies the temperature and the softmax over the question's+options, because only it knows how many options each row has.+"""++from collections.abc import Set as AbstractSet++import torch+from vllm.config import VllmConfig+from vllm.model_executor.layers.pooler import Pooler, PoolingParamsUpdate+from vllm.model_executor.layers.pooler.tokwise import AllPool+from vllm.model_executor.models.interfaces_base import default_pooling_type+from vllm.model_executor.models.qwen3_5 import Qwen3_5ForCausalLM+from vllm.tasks import PoolingTask+from vllm.v1.outputs import PoolerOutput+from vllm.v1.pool.metadata import PoolingMetadata+++class JevK5Pooler(Pooler):+ def __init__(self, lm_head: torch.nn.Module, letter_token_ids: list[int]) -> None:+ super().__init__()+ self.lm_head = lm_head+ self.letter_token_ids = letter_token_ids+ self.all_pool = AllPool()++ def get_supported_tasks(self) -> AbstractSet[PoolingTask]:+ return {"plugin"}++ def get_pooling_updates(self, task: PoolingTask) -> PoolingParamsUpdate:+ return PoolingParamsUpdate()++ def forward(self, hidden_states: torch.Tensor, pooling_metadata: PoolingMetadata) -> PoolerOutput:+ rows = self.all_pool(hidden_states, pooling_metadata)+ # 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]+++@default_pooling_type(seq_pooling_type="LAST", tok_pooling_type="ALL")+class JevK5ForDecision(Qwen3_5ForCausalLM):+ is_pooling_model = True++ def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:+ super().__init__(vllm_config=vllm_config, prefix=prefix)+ config = vllm_config.model_config.hf_text_config+ self.pooler = JevK5Pooler(self.lm_head, letter_token_ids=list(config.jevk5_letter_token_ids))diff --git a/products/ml_inference/packages/kev-vllm/kev_vllm/plugin.py b/products/ml_inference/packages/kev-vllm/kev_vllm/plugin.pyindex 9ea253d3bfdc..85874fc90281 100644--- a/products/ml_inference/packages/kev-vllm/kev_vllm/plugin.py+++ b/products/ml_inference/packages/kev-vllm/kev_vllm/plugin.py@@ -1,13 +1,19 @@-"""Entry points vLLM discovers: `vllm.general_plugins` registers the model class, `vllm.io_processor_plugins` names-the IO processor. Both stay lazy so that importing this module never initializes CUDA."""+"""Entry points vLLM discovers: `vllm.general_plugins` registers the model classes, `vllm.io_processor_plugins` names+the IO processors. A checkpoint's config picks one of each (`architectures`, `io_processor_plugin`). Both stay lazy so+that importing this module never initializes CUDA."""def register() -> None:from vllm import ModelRegistryModelRegistry.register_model("KevForDecision", "kev_vllm.model:KevForDecision")+ ModelRegistry.register_model("JevK5ForDecision", "kev_vllm.jevk5_model:JevK5ForDecision")+# Dotted, not `module:attr`: vLLM resolves IO-processor plugins with importlib on the last dot.def io_processor() -> str:- # Dotted, not `module:attr`: vLLM resolves IO-processor plugins with importlib on the last dot.return "kev_vllm.io_processor.KevIOProcessor"+++def jevk5_io_processor() -> str:+ return "kev_vllm.jevk5_io_processor.JevK5IOProcessor"diff --git a/products/ml_inference/packages/kev-vllm/pyproject.toml b/products/ml_inference/packages/kev-vllm/pyproject.tomlindex 84d941993814..eab14fff3b2b 100644--- a/products/ml_inference/packages/kev-vllm/pyproject.toml+++ b/products/ml_inference/packages/kev-vllm/pyproject.toml@@ -22,12 +22,15 @@ export = ["kev", "peft>=0.21", "accelerate>=1.15", "safetensors>=0.5", "huggingf[project.scripts]kev-vllm-export = "kev_vllm.export:main"kev-vllm-parity = "kev_vllm.parity:main"+jevk5-vllm-export = "kev_vllm.jevk5_export:main"+kev-vllm-checkpoint = "kev_vllm.checkpoint:main"[project.entry-points."vllm.general_plugins"]kev = "kev_vllm.plugin:register"[project.entry-points."vllm.io_processor_plugins"]kev = "kev_vllm.plugin:io_processor"+jevk5 = "kev_vllm.plugin:jevk5_io_processor"[dependency-groups]dev = ["pytest>=8", "ruff>=0.14"]diff --git a/products/ml_inference/packages/kev-vllm/serving/Caddyfile b/products/ml_inference/packages/kev-vllm/serving/Caddyfilenew file mode 100644index 000000000000..e6f7ec0c1a81--- /dev/null+++ b/products/ml_inference/packages/kev-vllm/serving/Caddyfile@@ -0,0 +1,19 @@+# The proxy in front of vLLM inside the serving image. PORT, VLLM_PORT and DECISION_BEARER come from bin/serve.sh.+{+ auto_https off+ admin off+}++:{$PORT} {+ @unauthorized {+ not header Authorization "Bearer {$DECISION_BEARER}"+ }+ @served path /pooling /health /metrics++ # A route keeps the written order; Caddy's default order would put the 404 before the proxy.+ route {+ respond @unauthorized 401+ reverse_proxy @served 127.0.0.1:{$VLLM_PORT}+ respond 404+ }+}diff --git a/products/ml_inference/packages/kev-vllm/tests/test_jevk5.py b/products/ml_inference/packages/kev-vllm/tests/test_jevk5.pynew file mode 100644index 000000000000..83accc38261d--- /dev/null+++ b/products/ml_inference/packages/kev-vllm/tests/test_jevk5.py@@ -0,0 +1,53 @@+import json+import math++import pytest++from kev_vllm import jevk5+from kev_vllm.kev_compat import SystemOneRequest, to_answers, to_record++STATE = {"order": "4411", "note": "Billed €40 twice, refund the duplicate"}+++ "question,descriptions",+ [+ ({"type": "noul", "instructions": "Refund due?"}, ["true: The proposition is true.", "false: The proposition is false."]),+ (+ {"type": "noul", "instructions": "Refund due?", "criteria": {"true": "It is due", "false": "It is not"}},+ ["true: It is due", "false: It is not"],+ ),+ (+ {"type": "choice", "instructions": "Team?", "criteria": {"billing": "Payments", "tech": None}},+ ["billing: Payments", "tech: tech"],+ ),+ ({"type": "score", "instructions": "How upset?", "criteria": ["calm", "furious"]}, ["0: calm", "1: furious"]),+ ],+)+def test_the_prompt_is_the_one_jevk5_was_trained_on(question, descriptions):+ parsed = SystemOneRequest.model_validate({"state": STATE, "questions": {"q": question}}).questions["q"]+ system, user = jevk5.messages(STATE, parsed)+ assert system == {"role": "system", "content": jevk5.SYSTEM}+ expected = {+ "evidence": STATE,+ "criterion": question["instructions"],+ "options": [{"letter": jevk5.LETTERS[i], "description": text} for i, text in enumerate(descriptions)],+ }+ assert user == {"role": "user", "content": json.dumps(expected, ensure_ascii=False)}+++def test_a_noul_answer_is_the_probability_of_true_although_true_takes_the_first_letter():+ request = SystemOneRequest.model_validate({"state": "s", "questions": {"refund": {"type": "noul", "instructions": "?"}}})+ _, meta = to_record(request)+ probs = jevk5.probabilities([2.0, 0.0, 9.0], request.questions["refund"], temperature=1.5, keys=meta[0]["keys"])+ p_true = 1 / (1 + math.exp(-2.0 / 1.5))+ assert probs == pytest.approx([1 - p_true, p_true])+ assert to_answers([probs], meta)["refund"]["noul"] == round(p_true, 2)+++def test_more_options_than_letters_are_refused():+ question = SystemOneRequest.model_validate(+ {"state": "s", "questions": {"q": {"type": "choice", "instructions": "?", "criteria": {str(i): None for i in range(17)}}}}+ ).questions["q"]+ with pytest.raises(ValueError, match="at most 16 options"):+ jevk5.messages("s", question)diff --git a/products/ml_inference/packages/kev-vllm/tests/test_kev_vllm_checkpoint.py b/products/ml_inference/packages/kev-vllm/tests/test_kev_vllm_checkpoint.pynew file mode 100644index 000000000000..6e3775ad8d77--- /dev/null+++ b/products/ml_inference/packages/kev-vllm/tests/test_kev_vllm_checkpoint.py@@ -0,0 +1,41 @@+import hashlib+import json+from pathlib import Path++import pytest++from kev_vllm.checkpoint import verify+++def write_checkpoint(tmp_path: Path, tamper: str | None = None) -> Path:+ weights = tmp_path / "model.safetensors"+ weights.write_bytes(b"weights")+ manifest = {"kev_run": "run", "files": {"model.safetensors": {"sha256": hashlib.sha256(b"weights").hexdigest()}}}+ if tamper == "no_files_table":+ del manifest["files"]+ (tmp_path / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")+ if tamper == "bytes":+ weights.write_bytes(b"weight5")+ if tamper == "missing":+ weights.unlink()+ return tmp_path+++def test_verify_accepts_a_checkpoint_that_matches_its_manifest(tmp_path: Path) -> None:+ assert verify(write_checkpoint(tmp_path))["kev_run"] == "run"++[email protected]("tamper", ["bytes", "missing"])+def test_verify_rejects_a_checkpoint_that_drifted_from_its_manifest(tmp_path: Path, tamper: str) -> None:+ with pytest.raises(ValueError, match=r"model\.safetensors"):+ verify(write_checkpoint(tmp_path, tamper))+++def test_verify_rejects_a_manifest_without_a_files_table(tmp_path: Path) -> None:+ with pytest.raises(ValueError, match="no files table"):+ verify(write_checkpoint(tmp_path, "no_files_table"))+++def test_verify_rejects_a_directory_without_a_manifest(tmp_path: Path) -> None:+ with pytest.raises(FileNotFoundError):+ verify(tmp_path)