Skip to content

Instantly share code, notes, and snippets.

@shiv4289
Created October 30, 2026 18:03
Show Gist options
  • Select an option

  • Save shiv4289/fd9170d3bdc0274261663247a42d258b to your computer and use it in GitHub Desktop.

Select an option

Save shiv4289/fd9170d3bdc0274261663247a42d258b to your computer and use it in GitHub Desktop.
llm-d chunked decode + vLLM PR #64536 (structured_output_prefill): CPU reproduction with docker compose

llm-d chunked decode + vLLM PR #64536 (structured_output_prefill)

A CPU-only reproduction for vllm-project/vllm#64536, which addresses vllm-project/vllm#64268.

The case: llm-d's sidecar can split one generation into short chunks (--decode-chunk-size). From the second chunk on, it continues the text so far as the final assistant message with continue_final_message: true. With structured outputs, vLLM's grammar restarts on every chunk, so the joined output is invalid (llm-d/llm-d-router#3642).

What runs (docker compose up):

Service What Port
vllm-pr vllm/vllm-openai-cpu:v0.32.0 with the Python sources of PR #64536 at 1d9c2dd8 overlaid at startup (compiled extensions from the image), HuggingFaceTB/SmolLM2-135M-Instruct 8202
sidecar-main llm-d sidecar built from llm-d-router e8d54cdb as is, --decode-chunk-size=5 8300
sidecar-flag the same plus sidecar-flag.patch (4 lines): sends structured_output_prefill: true on later chunks of constrained requests 8301

The sidecars share the vLLM container's network, as they would share a pod.

Run

docker compose up -d --build   # first run: builds the sidecars, downloads the PR sources and the model
./test.sh                      # needs curl and jq
docker compose down

test.sh sends the same requests (temperature 0, max_tokens 60) through both sidecars and checks the joined output: valid JSON for json_object / json_schema, a full match for choice / regex. Expected: main is INVALID for every constraint, main+patch is VALID. Output from a clean run (fresh build, x86_64 laptop CPU):

json_object  main        INVALID "{\n    \"city\":{\n        \"name\":{\n            \"type\":{\"type\":\"string\",\"{\"typ
json_object  main+patch  VALID   "{\n    \"city\": \"Paris\",\n    \"country\": \"France\"\n}\n"
json_schema  main        INVALID "{\n  \"city\":{\n    \"city\":{\n      \"city\":{\n        \"city\":{\n          \"city\"
json_schema  main+patch  VALID   "{\n  \"city\": \"Paris\",\n  \"country\": \"France\"\n}\n"
choice       main        INVALID "The capital of France isThe capital of France isThe capital of France isThe capital of Fr
choice       main+patch  VALID   "The capital of France is Paris\n"
regex        main        INVALID "123-4567-1234-1234-1234-1234-1234-1234-1234-1234-1234-1234-1\n"
regex        main+patch  VALID   "123-456-7890\n"

Notes

  • CPU only, xgrammar backend, VLLM_USE_V2_MODEL_RUNNER=0 (same as the PR's own validation). Not covered: GPU, reasoning models, guidance and outlines backends.
  • To test another build of the PR (for example on GPU), run your own vLLM with the PR on port 8000 and start only the two sidecars in its network namespace, or run the sidecars on the same host with --model-server-port pointing at it.
  • The patch is an experiment, not a proposed llm-d change: it detects constrained requests with a string check. llm-d/llm-d-router#3685 skips chunking for these requests on current vLLM versions.
# Reproduce: llm-d chunked decode + structured outputs, with and without vLLM PR #64536's
# `structured_output_prefill`. CPU only. See README.md.
services:
vllm-pr:
image: vllm/vllm-openai-cpu:v0.32.0
entrypoint: ["bash", "/repro/vllm-pr-entrypoint.sh"]
environment:
VLLM_CPU_KVCACHE_SPACE: "1"
VLLM_USE_V2_MODEL_RUNNER: "0"
shm_size: 2g
volumes:
- ./:/repro:ro
- hf-cache:/root/.cache/huggingface
ports:
- "8202:8000" # vLLM directly
- "8300:8300" # sidecar, llm-d main as is
- "8301:8301" # sidecar, llm-d main + sidecar-flag.patch
# The sidecars share vLLM's network namespace, like containers in one pod:
# the sidecar always reaches the model server on localhost.
sidecar-main:
build: {context: ., dockerfile: Dockerfile.sidecar, args: {WITH_FLAG: "0"}}
network_mode: "service:vllm-pr"
command: ["--port=8300", "--model-server-port=8000", "--decode-chunk-size=5", "--secure-serving=false"]
depends_on: [vllm-pr]
sidecar-flag:
build: {context: ., dockerfile: Dockerfile.sidecar, args: {WITH_FLAG: "1"}}
network_mode: "service:vllm-pr"
command: ["--port=8301", "--model-server-port=8000", "--decode-chunk-size=5", "--secure-serving=false"]
depends_on: [vllm-pr]
volumes:
hf-cache:
# llm-d sidecar built from a pinned llm-d-router commit.
# WITH_FLAG=1 applies sidecar-flag.patch, which sends `structured_output_prefill: true`
# on chunks after the first for constrained requests (vLLM PR #64536).
FROM golang:1.27.3 AS build
ARG LLMD_COMMIT=e8d54cdbdb3c5edb58ebfd362564d9679cea544e
ARG WITH_FLAG=0
WORKDIR /src
RUN git init -q . \
&& git remote add origin https://github.com/llm-d/llm-d-router.git \
&& git fetch -q --depth 1 origin "$LLMD_COMMIT" \
&& git checkout -q FETCH_HEAD
COPY sidecar-flag.patch /tmp/sidecar-flag.patch
RUN if [ "$WITH_FLAG" = "1" ]; then git apply /tmp/sidecar-flag.patch; fi
RUN CGO_ENABLED=0 go build -o /pd-sidecar ./cmd/pd-sidecar
FROM gcr.io/distroless/static:nonroot
COPY --from=build /pd-sidecar /pd-sidecar
ENTRYPOINT ["/pd-sidecar"]
diff --git a/pkg/sidecar/proxy/decode.go b/pkg/sidecar/proxy/decode.go
index 134edb9d..621594c9 100644
--- a/pkg/sidecar/proxy/decode.go
+++ b/pkg/sidecar/proxy/decode.go
@@ -228,6 +228,10 @@ func (s *Server) runChunkedDecodeFromMap(w http.ResponseWriter, r *http.Request,
delete(chunkReq, reqcommon.FieldKVTransferParams)
chunkReq[reqcommon.FieldContinueFinalMessage] = true
chunkReq[reqcommon.FieldAddGenerationPrompt] = false
+ // Experiment: opt in to vLLM PR #64536 for constrained requests.
+ if rf, ok := body["response_format"]; (ok && rf != nil && !strings.Contains(strings.ReplaceAll(fmt.Sprint(rf), " ", ""), `"type":"text"`)) || body["structured_outputs"] != nil {
+ chunkReq["structured_output_prefill"] = true
+ }
content, _ := json.Marshal(prefix + textAccum.String())
finalMessage[reqcommon.FieldContent] = content
message, err := json.Marshal(finalMessage)
#!/usr/bin/env bash
# Sends the same constrained requests through both sidecars (5-token chunks) and checks the output.
set -uo pipefail
MODEL=HuggingFaceTB/SmolLM2-135M-Instruct
until curl -sf localhost:8202/v1/models >/dev/null; do echo "waiting for vLLM on :8202 ..."; sleep 5; done
check() { # $1 label, $2 extra request fields (JSON), $3 prompt, $4 validator (jq | regex:<re>)
for port in 8300 8301; do
out=$(jq -n --arg m "$MODEL" --arg q "$3" --argjson x "$2" \
'{model:$m, temperature:0, max_tokens:60, messages:[{role:"user",content:$q}]} + $x' |
curl -s "localhost:$port/v1/chat/completions" -H 'Content-Type: application/json' -d @-)
text=$(jq -j '.choices[0].message.content // ("ERROR " + tostring)' <<<"$out")
case "$4" in
jq) printf '%s' "$text" | jq -e . >/dev/null 2>&1 && ok=VALID || ok=INVALID ;;
regex:*) [[ "$text" =~ ^${4#regex:}$ ]] && ok=VALID || ok=INVALID ;;
esac
[ $port = 8300 ] && side="main " || side="main+patch"
printf '%-12s %s %-7s %s\n' "$1" "$side" "$ok" "$(jq -Rs . <<<"$text" | cut -c1-90)"
done
}
check json_object '{"response_format":{"type":"json_object"}}' \
"Give me a JSON object describing Paris with keys city, country, population." jq
check json_schema '{"response_format":{"type":"json_schema","json_schema":{"name":"city","schema":{"type":"object","properties":{"city":{"type":"string"},"country":{"type":"string"}},"required":["city","country"]}}}}' \
"Describe Paris as JSON." jq
check choice '{"structured_outputs":{"choice":["The capital of France is Paris","The capital of France is Lyon"]}}' \
"What is the capital of France? Answer with a full sentence." 'regex:The capital of France is (Paris|Lyon)'
check regex '{"structured_outputs":{"regex":"[0-9]{3}-[0-9]{3}-[0-9]{4}"}}' \
"Give me a US phone number." 'regex:[0-9]{3}-[0-9]{3}-[0-9]{4}'
#!/usr/bin/env bash
# Runs inside vllm/vllm-openai-cpu:v0.32.0: overlays the Python sources of vLLM PR #64536
# (pinned commit) on the installed package, keeping the image's compiled extensions.
set -euo pipefail
PR_REPO=${PR_REPO:-stdlibstring/vllm}
PR_SHA=${PR_SHA:-1d9c2dd85b56b4d7fc7112328b34f869bf7813cd}
MODEL=${MODEL:-HuggingFaceTB/SmolLM2-135M-Instruct}
SITE=/opt/venv/lib/python3.12/site-packages/vllm
if [ ! -f /tmp/.pr-overlay-done ]; then
echo "Overlaying ${PR_REPO}@${PR_SHA} Python sources on ${SITE}"
/opt/venv/bin/python - "$PR_REPO" "$PR_SHA" "$SITE" <<'PY'
import io, os, sys, tarfile, urllib.request
repo, sha, site = sys.argv[1:]
url = f"https://codeload.github.com/{repo}/tar.gz/{sha}"
n = 0
with urllib.request.urlopen(url) as resp, tarfile.open(fileobj=resp, mode="r|gz") as tar:
for m in tar:
parts = m.name.split("/", 2) # <repo>-<sha>/vllm/...
if len(parts) < 3 or parts[1] != "vllm" or not m.isfile() or not m.name.endswith(".py"):
continue
dst = os.path.join(site, parts[2])
os.makedirs(os.path.dirname(dst), exist_ok=True)
with open(dst, "wb") as f:
f.write(tar.extractfile(m).read())
n += 1
print(f"overlaid {n} files")
PY
# The PR's base needs orjson, which the v0.32.0 image lacks.
uv pip install -q --python /opt/venv/bin/python orjson
touch /tmp/.pr-overlay-done
fi
exec /opt/venv/bin/vllm serve "$MODEL" --max-model-len 2048
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment