TensorRT-LLM icon indicating copy to clipboard operation
TensorRT-LLM copied to clipboard

[Bug]: `/metrics` (iteration-stats) route blocks the serve event loop — a 2 s Prometheus scrape inflates request latency 5–60× and cuts prefill throughput ~5× (4× RTX 5060 Ti TP4, Qwen3.5 hybrid-GDN NVFP4 27B, 1.3.0rc29)

Open sean640112 opened this issue 2 months ago • 9 comments

Update (2026-10-09): the root cause is not sm120. The "fixed" per-request cost comes from the /metrics iteration-stats route blocking the serve event loop: a 2 s Prometheus scrape inflates request latency 5–60× and cuts prefill throughput ~5×. Controlled A/B, py-spy stacks and the Prometheus-side numbers are in the follow-up comment below.

~6 s fixed per-request latency floor on sm120 (4× RTX 5060 Ti, TP4) with a Qwen3.5 hybrid-GDN 27B NVFP4 checkpoint

Summary

On a 4× RTX 5060 Ti (sm120) box serving a dense hybrid GDN + full-attention 27B NVFP4 checkpoint with trtllm-serve (PyTorch backend, TP4), we measure a ~6 s per-request floor on time-to-first-token that is independent of prompt length. A 212-token request takes 6.06 s to first token (8.0 s total), and the floor persists at every length we tested (212 → 59,571 tokens). Requests are reproducible to ±5 ms across 12 measurements in 3 separate server starts.

The same hardware, same checkpoint, same prompt, same client, served by SGLang gives 0.26–0.30 s for the identical request. trtllm-serve therefore looks ~20× slower on short requests, while its marginal prefill throughput is only ~2.6× lower (~2,143 tok/s vs ~5,600 tok/s).

We have ruled out MTP/spec-decode, scheduler policy, max_seq_len, chunked prefill, the CUDA caching allocator, and thinking-mode as causes (details below). We would like to know whether this per-request floor is expected on sm120 for hybrid GDN models, or a bug — and which knob/diagnostic we should look at next. We are happy to run any instrumentation you suggest.

Environment

GPU 4× NVIDIA GeForce RTX 5060 Ti 16 GB, compute capability 12.0 (sm120), TP=4
Driver 610.57.04
CUDA toolkit 13.3 (nvcc 13.3, CUDA_HOME=/usr/local/cuda-13.3)
OS / Python Linux, Python 3.12.11 (venv)
TensorRT-LLM 1.3.0rc29.dev202609240000 (nightly from 2026-09-24; PyPI 1.2.1 does not contain modeling_qwen3_5.py, hence nightly)
torch 2.14.0+cu132
flashinfer-python 0.6.18
triton 3.8.0
nvidia-cutlass-dsl 4.8.0.dev0
tensorrt / tensorrt_cu13 10.14.1.48.post1
MPI OpenMPI 5.0.10 (mpi4py bootstrap path)
Model nvidia/Qwen3.8-27B-NVFP4 — architectures: ["Qwen3_5ForConditionalGeneration"], model_type: qwen3_5; 64 layers, hidden 5120, 24 Q heads, 4 KV heads
Quantization ModelOpt MIXED_PRECISION: FP8 per-tensor on 208 layers (block_size absent) + NVFP4 group_size: 16 on 193 layers, kv_cache_quant_algo: null

Note on the attention backend: your hardware support matrix lists sm120 as supporting NVFP4 / MXFP4 / FP8 (per-tensor) / FP8 KV cache, which covers this checkpoint's formats — so the quantization scheme itself should be fully supported on sm120.

How to reproduce

Server (the mpirun -n 1 wrapper and OMPI_MCA_* are needed on this host because import tensorrt_llm otherwise blocks in the mpi4py MPI.COMM_WORLD initialization, and this host's own hostname resolves to loopback only):

export CUDA_HOME=/usr/local/cuda-13.3
export OMPI_MCA_btl_tcp_if_include=lo OMPI_MCA_oob_tcp_if_include=lo
mpirun -n 1 --oversubscribe trtllm-serve serve /path/to/Qwen3.8-27B-NVFP4 \
  --host 127.0.0.1 --port 1234 --tp_size 4 \
  --max_seq_len 140000 --max_batch_size 8 \
  --served_model_name qwen3.8-27b \
  --free_gpu_memory_fraction 0.80 \
  --extra_llm_api_options opts.yaml

opts.yaml:

enable_chunked_prefill: true
max_num_tokens: 8192
speculative_config:
  decoding_type: MTP
  max_draft_len: 3
  speculative_model: /path/to/Qwen3.8-27B-NVFP4

Client — a minimal stdlib-only streaming client (this is the "probe" used for every number below; it measures the first chunk that carries choices[0].text/delta.content):

import json, time, urllib.request
prompt = open("/path/to/corpus.txt").read()[:600]          # → 212 tokens
body = {"model": "qwen3.8-27b", "prompt": prompt, "max_tokens": 1, "temperature": 0, "stream": True}
req = urllib.request.Request("http://127.0.0.1:1234/v1/completions",
        data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
t0 = time.time(); ttft = None
with urllib.request.urlopen(req, timeout=900) as r:
    for raw in r:
        s = raw.decode().strip()
        if not s.startswith("data: "): continue
        if s[6:] == "[DONE]": break
        d = json.loads(s[6:])
        ch = d.get("choices") or []
        if ch and ch[0].get("text"):
            ttft = time.time() - t0; break
print("TTFT", ttft)

Measured results (same probe, same prompts, same box)

prompt tokens path TRT-LLM stream TTFT TRT-LLM non-stream total SGLang stream TTFT SGLang non-stream total
212 completions 6.053–6.062 s (n=5) 7.995–8.035 s 0.262 s 0.304 s
222 chat (medium template) 12.11 – 22.21 s (unstable across restarts) 14.06 – 26.19 s 0.268 s —
7,172 completions 10.10 s 12.02 s 0.243 s cached 1.84 s cached
12,131 completions 12.12 s 14.06 s — —
28,008 completions — 20.13 s — 6.15 s cached
59,571 completions — 36.26 s — —
65,032 chat 56.52 s 56.45 s — —

("cached" = the SGLang side hit its radix prefix cache on the shared corpus prefix, so those cells are not a like-for-like prefill comparison.)

Least-squares fit of the completions path (total = C + N/R, 5 points spanning 212 → 59,571 tokens): C = 8.10 s, R = 2,143 tok/s, R² = 0.9966 — i.e. a very large constant plus a modest rate term. (The streaming TTFT is ≈ 1.9 s lower at every point, i.e. TTFT ≈ 6.1 s + N/2143.)

For reference, an independent client (vLLM's bench serve against the same server) measured prefill throughput of 453 / 1,014 / 1,302 tok/s at 8K / 32K / 64K with meanTTFT 16.15 / 29.28 / 46.44 s, i.e. the same shape: mostly a constant, with the rate part improving with length.

The SGLang side on this box (same checkpoint, TP4, DFlash2, fp8 KV, same client) measures ~5,600 tok/s marginal prefill and a per-request overhead of ≲0.3 s. So the fixed component, not the rate, is what dominates short requests for us.

What we ruled out (each was an actual A/B on a server restart)

Variant tiny-request TTFT 8K-prefill
baseline (MTP on, chunked prefill on, max_seq_len 140000) 6.06 s (one earlier start gave 0.139 s — unreproducible) 453 tok/s
speculative_config removed (MTP off) 6.057 s 453 tok/s (identical)
scheduler_config.capacity_scheduler_policy: MAX_UTILIZATION 6.059 s 453 tok/s (identical)
max_seq_len 140000 → 32768 6.056 s 453 tok/s (identical)
enable_chunked_prefill off 6.056 / 6.061 / 6.055 s —
PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (i.e. exactly what the log recommends) 6.054 / 6.058 / 6.062 / 6.058 s —
chat_template_kwargs: {"enable_thinking": false} 12.121 s vs 12.120 s with thinking on — no change —

Prompt length is irrelevant to the constant: 212 tokens → 6.06 s and 59,571 tokens → 36.26 s both sit on the same line.

Log evidence

Selected lines from the server log (PyTorch backend, verbose):

[W] [thop][RANK 0..3] Attention workspace size is not enough, increase the size from 0 bytes to 75558912 bytes
[W] [_torch][RANK 0] It is recommended to incl. 'garbage_collection_threshold:0.???' or 'backend:cudaMallocAsync' or 'expandable_segm…'
[W] [_torch][RANK 0] Partial reuse is not supported for mamba hybrid models, disabling partial reuse
[W] [_torch][RANK 0] [AutoTuner] trtllm::nvfp4_gemm::gemm using the fallback tactic, due to cache miss on input shapes=(torch.Size([4, 2560]), …
[I] [_torch][RANK 0] lm_head quant entry (NVFP4) dropped: unsupported configuration for quantized LMHead (requires SM100/103/SM120, untied embedding…
[I] [_torch][RANK 0] Run generation-only CUDA graph capture (advanced sampling) for batch size=3, draft_len=3, max_seq_len=140000
[W] [serve] Resource governor is disabled: the executor backend does not provide a resource_governor_queue …
[I] [_startup][RANK 0] [startup][pid=…] executor_creation: done, total=147.844s, unattributed=0.123s | configuration_and_distributed_init=0.347s,
    model=87.365s, sampler=0.000s, profiling_kv_cache_allocation=0.012s, spec_resource_manager=0.000s, drafter=0.000s,
    profiling_executor_creation=34.979s, memory_profiling_and_capacity=9.189s, profiling_resource_teardown=0.471s,
    final_kv_cache_allocation=0.018s, final_executor_creation=15.338s, executor_start_worker=0.001s
[I] [batchmgr][RANK 0] Max KV cache blocks per sequence: 4376 [window size=140008], tokens per block=32, primary blocks=5272, max sequence length=140008
[I] [warmup][pid=571366][rank=0][purpose=final_executor][pass=2] cuda_graph_capture: done in 7.1s

(The CUDA graph captures happen once during startup, not per request — we checked.)

Questions

  1. Is a ~6 s per-request floor expected on sm120 for hybrid (GDN / mamba-style) models with the PyTorch backend, or is this a bug?
  2. Is there a configuration we are missing that governs per-request fixed cost for hybrid models — e.g. something around the GDN/mamba state cache, the attention workspace growth warning above, or a sm120-specific attention backend selection (attn_backend currently resolves to TRTLLM)?
  3. Does this relate to any of the existing sm120 / GDN threads, e.g. #15634 (Qwen3-Next Gated-DeltaNet on consumer Blackwell), #19376 (flashinfer GDN prefill on sm120/121), #15853 (B12x NVFP4 JIT on SM120/SM121), or #18813 ("Resolve the runtime JIT issue")? If a duplicate exists, please close this and point us at the right thread — we will happily add our data there.
  4. Which instrumentation would you like in order to localize the constant? We can enable enable_iter_perf_stats/return_perf_metrics, print_iter_log, NVTX, or run any branch you point us to — the box is available for A/B testing.

Extra context

  • This is a 4-card 16 GB consumer Blackwell box used both for this evaluation and for production inference, so we can A/B TRT-LLM vs SGLang on the same hardware within minutes.
  • Everything above was measured with mon-gpu-sampler-type monitoring stopped and no other load on the GPUs; each server start took ~145–170 s to become ready.
  • If useful we can provide the full raw logs, the exact client scripts, and a matching SGLang run for comparison.

sean640112 avatar Sep 24 '26 15:09 sean640112

Probe done, single GPU numbers below. This isolates the GDN prefill cost independent of the TP4, mpirun and NVFP4 27B variables.

Env is TensorRT-LLM 1.3.0rc29, torch 2.14.0, single RTX PRO 6000 Blackwell sm120. Model is Qwen/Qwen3.5-2B, qwen3_5, same hybrid GDN family, served via trtllm-serve at TP1.

Results, TTFT over 5 runs

With FlashInfer prefill on, the default, the 212 tok prompt with max_tokens 1 took 16.1 to 17.5 ms and the 4096 tok prompt took 49.6 to 53.9 ms. With FlashInfer prefill off, TLLM_USE_FLASHINFER_GDN_PREFILL=0, they took 17.8 to 19.1 ms and 49.9 to 52.5 ms.

Stream closes within 0.1 ms of TTFT, single token responses. FlashInfer is the default, see the server log.

Takeaways

On one card, GDN prefill is measured in milliseconds, nowhere near the 6.1 s floor. That floor comes from the TP4 path, the mpirun loopback setup, or something about the NVFP4 27B ckpt.

FlashInfer toggle moves latency only about 2 ms either way here.

Server log also flags an Autotuner cache miss, falling back, for nvfp4_gemm on shape 4 by 2560, which fits a small M shape, just FYI.

Next steps to nail down the 6.1 s

Serve the same 2B at TP4 on the same box, which shows if it is the TP4 path.

Short nsys capture around a single 212 tok request, where GPU busy vs. wall clock shows GDN kernels vs. gaps.

If the GPUs are idle for about 6 s, py-spy dump on rank 0 should show exactly where the wall clock goes.

LaelaZorana avatar Oct 08 '26 22:10 LaelaZorana

Follow-up: the per-request latency floor and the prefill throughput cap are both caused by scraping the /metrics route, not by sm120

Thanks for the earlier guidance. Following it, we ran controlled A/Bs on the same binary and found that the "fixed per-request cost" comes from the Prometheus scrape of /metrics, and that it degrades more than first-token latency.

Setup: TRT-LLM 1.3.0rc29, sm120, 4× RTX 5060 Ti 16G, TP4, Qwen3.8-27B-NVFP4 (hybrid GDN), mpirun -n 1 trtllm-serve ... --tp_size 4.

A. Short requests (212-token prompt, reproducible ±5 ms)

engine on 127.0.0.1:1234 (Prometheus scrapes every 2 s) same engine on 127.0.0.1:1235 (nothing scrapes it)
212-token, non-stream 7.74 / 8.07 / 8.07 s 0.137 / 0.137 / 0.178 s
stream TTFT 6.060 / 6.060 / 6.060 s 0.139 / 0.138 / 0.140 s

B. Prefill throughput (canonical vllm bench serve, --dataset-name random, 2 prompts, concurrency 1, output len 1)

input len scrape active not scraped
8,192 488 tok/s (Mean TTFT 14,996 ms) 2,514 tok/s (2,911 ms)
32,768 1,081 tok/s (27,476 ms) 2,386 tok/s (12,449 ms)
65,536 1,452 tok/s 2,177 tok/s

So a 2-second monitoring scrape costs anywhere from ~5× to ~60× depending on the request shape.

Prometheus side (job_name: llm, scrape_interval: 2s, scrape_timeout: 1500ms, metrics_path: /metrics), its own scrape_duration_seconds{job="llm"}:

  • with our TRT-LLM server up: every scrape times out at 1.5003–1.5012 s (up=0)
  • with our SGLang server on the same port: 0.060–0.063 s (up=1)

Mechanism: the single serve event loop is blocked inside the /metrics handler, which awaits engine stats through a blocking RPC. py-spy from the frontend process shows the same stack at 0.6 s / 3 s / 6 s into a request:

get_iteration_stats (serve/openai_server.py) -> get_stats_async (llmapi/llm.py)
  -> aget_stats (executor/proxy.py) -> _call_sync (executor/rpc/rpc_client.py) -> Future.result()

TTFT ≈ 3 × 2.02 s and non-stream total ≈ 4 × 2.02 s — the scrape interval is the quantum. It also explains why the engine looked idle while requests were slow: GPUs at ~0% util, rank 0's executor parked in queue.get(), and the other ranks spinning in the per-iteration request-count broadcast — the request had not reached the engine yet.

Mitigations we tested:

  1. Not scraping the port → full recovery (tables above).
  2. enable_iter_perf_stats: true in the extra LLM API options → short requests recovered (0.184 s / TTFT 0.140 s) while Prometheus kept scraping every 2 s, but prefill did not (8K stayed at 488 tok/s vs 2,514 clean). So that flag is not a substitute for fixing the route.

The underlying hazard looks like the stats route awaiting a blocking RPC on the serve event loop (the source comment in that path mentions nvbug 6102381). Making /metrics non-blocking by default — or documenting that Prometheus should scrape /prometheus/metrics rather than the JSON stats route — would prevent a monitoring scrape from inflating latency and prefill cost by 5–60×.

Happy to share py-spy dumps, full server args, or run a patched build on this exact setup (4× sm120 consumer cards, TP4) if that helps.

Thanks again, @LaelaZorana — this was filed half expecting it to go unanswered, so your reply was a pleasant surprise, and it is what led us to run the A/B that found the real cause.

sean640112 avatar Oct 09 '26 07:10 sean640112

When the direct JSON /metrics route waits for an empty stats queue, the proxies synchronously wait for RPC and block the HTTP event loop. This fix lets the caller await RPC on the existing client loop while preserving unread records. On a real RTX 5060 Ti running Qwen2.5-1.5B BF16, median client first-text latency under a deliberately overlapping scrape fell from 2020.05 ms to 32.54 ms; no-scrape controls remained about 33 ms.

First nonempty text SSE latency Before median / p95 (ms) After median / p95 (ms)
Overlapping /metrics 2020.05 / 2027.40 32.54 / 45.46
No-scrape control 33.05 / 45.38 32.70 / 46.03

Would an engineer approve this RPC/iterator scope for a PR? The implementation and DCO commits are available in the linked fork.

Experiment design, periodic scrape result, and limits

Six prespecified paired server restarts alternate AB/BA; each server runs ten fixed prompts per condition (60 requests per table cell). A trial drains stats, prewarms three separate connection pools, idles 100 ms, then starts scrape at 0 ms, generation at 50 ms and health at 100 ms. All 120 intended scraped-generation starts occurred while the scrape was in flight; no failed/late trials were selected out. The mean of six block-level differences-in-differences was 1983.85 ms, with a 10,000-resample paired-block percentile 95% interval of [1981.05, 1986.92] ms. This interval describes restart variability within this single-machine session.

A secondary, fixed low-load workload offered requests about every 3.7 s and scrape ticks every 2 s (three pairs, 25 requests/cell). Scraped first-text median was 34.46 → 34.53 ms; descriptive p95 was 1362.30 → 47.73 ms. With a one-in-flight scrape cap, before accepted 21/45 ticks and skipped 24; after accepted all 45. This does not establish a saturated-throughput gain.

Collision /health median fell from 1935.03 to 0.87 ms. /metrics total response median was 4034.26 → 108.86 ms; its full response time includes more than the blocking RPC wait and is not GPU execution time. All 376 generations completed without errors; 188 cross-version pairs matched payload, full generated text, finish markers and usage. Token IDs are not returned in this API mode.

Serving uses the real GenerationExecutorProxy, TP1, eager, 64 output tokens, KV prefix reuse disabled, enable_iter_perf_stats=true, return_perf_metrics=false, and the official external MPI launcher. No synthetic worker delay or altered RPC timeout is injected. Python base is 681cff123; the official native wheel 1.4.0rc1.dev202610140007 (Torch 2.14.0+cu132) is 13 commits older, with identical native binary hashes in both arms. This is a single-card mechanism reproduction, not the reporter's four-card TP4 27B deployment or a kernel-speedup claim; buffered metrics paths are outside scope.

An earlier campaign stopped after one server following a health connection error near the five-second keep-alive boundary (41 successful generations, one HTTP error). The observations are consistent with an idle-close race; no packet trace establishes the exact TCP sequence. Its records are retained and excluded as a whole; V2 only shortens client idle expiry to two seconds and reruns all six pairs. Two V2 metadata description strings retain old V1 labels; the executable hash and frozen V2 protocol identify the actual two-second policy.

Correctness coverage and assistance disclosure

The original production source fails all 12 targeted regressions; the patch passes 52 CPU cases, including eight real HMAC/ZMQ transport cases. Another 37 adjacent checks pass with two existing flaky-test skips. Coverage retains cancellation, errors, shutdown, concurrent consumption and shared-backlog retention: consuming A from [A, B], then fetching C, preserves [B, C]. Cancellation clears the client request without claiming to cancel server work. Public signatures are unchanged.

The latest commit only stabilizes two tests with explicit response-release gates. Under the same controlled 200 ms observer delay, 13 selected cases fail before and pass after; the ordinary full suite still passes 52 cases. Production files and case identities are unchanged. DCO sign-offs and changed-file pre-commit checks are present. AI tools assisted implementation, testing, and documentation.

Lewis-panda avatar Oct 14 '26 06:10 Lewis-panda

Updated the proposal above with real GPU validation on one RTX 5060 Ti, Qwen2.5-1.5B BF16:

  • Deliberately overlapping scrape: median first-text latency 2,020 → 32.5 ms (six paired server restarts).
  • Periodic scrape every 2 s, fixed low load: median essentially unchanged, 34.46 → 34.53 ms; descriptive sample p95 1,362 → 47.7 ms (three pairs, 25 requests per condition).

@sean640112, you mentioned being willing to test a patched build. If you have a chance, could you try the full patch (branch) on your original TP4 setup? That configuration remains unverified by this work.

Lewis-panda avatar Oct 14 '26 09:10 Lewis-panda

Reporter here — we ran your full patch on the original TP4 setup; the prefill half recovers too, not just the request floor.

Thanks for the follow-up, and for saying explicitly that this configuration was unverified by your work. We took the full patch (f7c62625d → ccf9425, branch fix/async-stats-rpc) back to the box from the report and ran a three-arm window, restarting the engine per arm. Only two variables: patched or not, scraped or not. Prometheus was left exactly as in production (job llm → 127.0.0.1:1234, scrape_interval 2s, scrape_timeout 1500ms); :1235 has no scraper.

Setup: 4× RTX 5060 Ti 16 GB, TP4, nvidia/Qwen3.8-27B-NVFP4 (hybrid GDN), trtllm-serve 1.3.0rc29.dev202609240000 (PyPI 1.2.1 has no modeling_qwen3_5.py), options exactly as in the report (enable_chunked_prefill: true, max_num_tokens: 8192, MTP max_draft_len: 3, max_seq_len 140000, free_gpu_memory_fraction 0.80). enable_iter_perf_stats left at its default false.

Your patch applies to 1.3.0rc29 as a file-level overlay — no rebuild: 3 pure-Python production files (executor/proxy.py, executor/rpc_proxy.py, new executor/rpc/iteration_result.py). The pre-patch context of both modified files matched; hunks applied with a −25 line offset, no fuzz, no rejects. Reverted afterwards.

Arm Serving port scraped stream TTFT (212 tok) non-stream total /health prefill 8K / 32K / 64K tok/s
A — unpatched yes (:1234) 6.065 s 8.079 s client timeout (10 s) 452.9 / 1,013.8 / 1,301.2
B — patched yes (:1234) 0.142 s 0.142 s 200 / 0.002 s 2,520.3 / 2,376.6 / 2,175.0
C — patched no (:1235) 0.138 s 0.143 s 200 / 0.002 s 2,523.0 / 2,384.2 / 2,175.0
D — patched + enable_iter_perf_stats: true yes (:1234) 0.144 / 0.138 / 0.137 s 0.196 / 0.138 / 0.139 s 200 / 0.002 s 2,499.8 / 2,382.1 / 2,170.6

Arm A reproduces the report on the same config (our earlier numbers: 6.060 s stream TTFT; prefill 488 / 1,081 / 1,452 tok/s). Prefill measured with vllm bench serve --backend openai --endpoint /v1/completions --dataset-name random --random-input-len {8192,32768,65536} --random-output-len 1 --num-prompts 2 --max-concurrency 1.

Three things beyond the single-card reproduction:

  1. The prefill half recovers too, and B ≈ C ≈ D. Your work establishes the request floor; on this deployment the throughput penalty also disappears — an active 2 s scrape on the serving port now costs nothing measurable (2,520 vs 2,523 tok/s at 8K against the unscraped arm), and both match the clean baseline we measured on this box before the patch (2,514 / 2,386 / 2,177). Your caveat that the periodic-scrape test "does not establish a saturated-throughput gain" still holds for that test — this is the same question answered from the deployment side. Arm D also shows the flag adds nothing on top of the patch here.
  2. The /metrics route itself stays slow on 1.3.0rc29, and up still reads 0. Even with the patch and enable_iter_perf_stats: true (arm D) the route still takes ~2.03 s at the endpoint — the same as without the flag, and we see no background-collector startup line in the engine log of this build — so Prometheus keeps timing out (up=0, scrape_duration_seconds oscillating between ~0.2 s and the 1.5 s ceiling) against the same 2 s / 1500 ms job. What the patch does fix is the collateral damage: /health went from a 10 s client timeout to 0.002 s while the scrapes kept coming. In your arm the route itself also got fast (4034 → 109 ms); on the older 1.3.0rc29 base we cannot reproduce that with either flag setting, so the route's own latency still looks like an open item (and possibly a version difference between our base and yours).
  3. No behavioural drift. A fixed greedy 64-token completion produced the same md5 in all four arms (and twice within each arm), and four engine runs produced no tracebacks.

On your PR question: from the outside we can only report that the change is observably clean here — same outputs, no errors, four engine starts. The RPC/iterator scope call is yours. We are happy to re-run against a merged build, or to re-test route latency on a newer base if you want the comparison against 1.3.0rc29. Raw logs, client scripts, the apply/revert scripts, and the py-spy stacks from our earlier forensics are available on request.

sean640112 avatar Oct 14 '26 14:10 sean640112

I should have flagged this earlier: @eopXD’s #19723 already makes aget_stats await the RPC without blocking the event loop, as part of a larger stats refactor. My patch overlaps with that part, so I won’t open a separate PR for it.

The GPU reproduction above and @sean640112’s TP4 results exercise the same code path, so they may be useful for #19723 as well. I’m happy to rerun the reproduction against #19723. If maintainers would prefer to resolve #19623 before the larger refactor lands, I can also provide a minimal patch limited to the proxy wait.

Separately, aget_kv_events still waits synchronously on the RPC in both proxies, and #19723 doesn’t change that path. I have a tested fix for it. @eopXD, would you prefer to include it in #19723, or should I propose it separately?

Lewis-panda avatar Oct 14 '26 17:10 Lewis-panda

Thanks — that answers the PR question, and good to know the stats path is already covered there.

We checked the claim against the PR, then tested #19723 itself on the reporter's deployment. Same setup as the numbers in my previous comment (4× RTX 5060 Ti, TP4, Qwen3.8-27B NVFP4, 1.3.0rc29 wheel, enable_iter_perf_stats=false, default scrape on :1234). The PR applies to our wheel as a file-level overlay — all 13 changed files are pure Python, no rebuild, one hunk needs fuzz 1:

arm short request (stream TTFT) prefill 8K / 32K / 64K (tok/s) /metrics endpoint
unpatched + scraped (repro) 6.065 s 452.9 / 1013.8 / 1301.2 14.1–18.3 s
your f7c62625d + scraped 0.142 s 2520.3 / 2376.6 / 2175.0 2.03 s
#19723 + scraped 0.140 / 0.136 / 0.138 s 2512.7 / 2383.5 / 2175.3 2.02 s
#19723, not scraped — 2477.0 / 2375.1 / 2175.5 2.02 s

Greedy 64-token output is byte-identical across every arm (md5 matches the unpatched baseline), 0 tracebacks, no EngineDead. So #19723 fixes the collateral damage exactly like your patch does on the same code path — consistent with what you said — but it does not make the /metrics route itself fast: it stays ~2.02 s whenever iteration stats are pending (≈0.2 s when the stats queue is empty). Your patch behaves the same, so this looks inherent to the legacy wait rather than to whichever async plumbing sits under it.

Two things that may be worth recording somewhere:

1. up is not a usable signal for this target in this build. up == 0 has a second, independent cause: /metrics returns application/json, so Prometheus 3.x rejects the target outright — received unsupported Content-Type "application/json" and no fallback_scrape_protocol specified for target. During the #19723 arm that same target scraped in 0.023–0.52 s and was still marked down. The reliable discriminator is scrape_duration_seconds pinned at the configured timeout (1.5 s here) versus well under it after the fix.

2. /prometheus/metrics needs a flag — and with it, monitoring works. The Prometheus-format endpoint is only mounted when return_perf_metrics=true (serve/openai_server.py: if self.generator.args.return_perf_metrics: self.mount_metrics()); with it off it 404s, and the only metrics route left is the JSON one. With the flag on and scrape config pointed at /prometheus/metrics we get a healthy target: 30/30 successful scrapes, scrape_duration 2–3 ms, short requests 0.139 s, 8K prefill 2,535 tok/s, identical greedy output — i.e. no throughput cost, and the JSON /metrics route is simply not scraped. That also corrects something I suggested earlier: pointing scrape config at that path is not enough on its own.

One caveat that cost us a measurement: when a scraper times out against the JSON route, the server-side handler keeps waiting on the stats RPC (the client disconnects, the blocking wait does not) — so the event loop stays clogged for tens of seconds after the scraper has given up, and anything measured in that window is contaminated. Our retest got clean numbers only by pointing the scrape config at /prometheus/metrics before starting the engine.

On aget_kv_events: agreed it is the same class of bug, and it is a live route here (/kv_cache_events exists in this build) — but nothing in this deployment polls it, so I have no end-to-end data to offer for or against. Happy to run the same harness on fe3e84e5 if that is useful, either now or after you and @eopXD decide where it lands.

If it helps #19723 move, I can re-run this harness against any revision you point at — overlaying a PR revision onto this wheel is straightforward and a full run is ~30 minutes.

sean640112 avatar Oct 14 '26 23:10 sean640112

Thanks @sean640112 for the careful A/Bs and for tracing this to the /metrics route, and thanks @Lewis-panda for the patch and the GPU reproduction. Sorry this went so long without a reply from us.

This is fixed by #20698, merged to main on 2026-10-23 (a cherry-pick of #20429 on release/1.3), and included in v1.4.0rc2 and later. The change is in get_iteration_stats in tensorrt_llm/serve/openai_server.py:

  • With enable_iter_perf_stats off, which is your configuration, /metrics now returns [] immediately instead of waiting on the stats queue.
  • With it on, the wait of up to 2 s runs on a dedicated thread, not on the event loop. Only one read runs at a time, and a scrape that arrives during a read returns [] right away, so frequent scrapes cannot pile up. If a scraper times out, its read finishes on that thread and hands its stats to the next scrape, so the event loop is no longer held after the scraper gives up.

Could you re-run your harness on v1.4.0rc2 or later, with your production scrape config? If short-request TTFT and prefill throughput match your #19723 arm, we'll close this issue.

On the other points:

  • For Prometheus, scrape /prometheus/metrics. /metrics returns iteration stats as JSON, not in the Prometheus text format. As you found, /prometheus/metrics is only mounted when return_perf_metrics: true is set.
  • aget_kv_events (/kv_cache_events) is not changed by #20698. It is a separate change from this issue.
  • #19723 is a broader refactor of iteration-stats reporting. This fix does not depend on it.

QiJune avatar Nov 16 '26 08:11 QiJune

Thanks @QiJune. I reran the reproduction with the official tensorrt_llm==1.4.0rc2.post1 wheel, without a source overlay, on an RTX 5060 Ti (TP1, BF16 Qwen2.5-1.5B-Instruct). The serving source matches the v1.4.0rc2 tag.

I no longer observe the seconds-long first-text stall in this local protocol, with iteration stats either disabled or enabled. Across three independent server restarts per mode:

Iteration stats 2-second scrape: first-text median / p95 No-scrape control: median / p95
Disabled 39.30 / 53.26 ms 40.50 / 52.61 ms
Enabled 40.08 / 53.38 ms 46.72 / 53.09 ms

These are descriptive pooled values, 50 requests per cell. Per-restart scrape p95 ranges were 52.44–54.05 ms (disabled) and 52.71–55.08 ms (enabled). The endpoint was JSON /metrics, with at most one scrape in flight.

In the deliberately overlapping scenario (generation starts 50 ms after the scrape), all 30 stats-enabled requests started while /metrics was pending and produced text before it returned; first-text p95 was 50.89 ms, maximum 54.24 ms. All 338 generations, including warmups, completed without request errors, with matched full-text/usage parity. The 13 official iteration-stats CPU tests also passed.

This supports the stall fix in #20698 for this TP1 setup. It is a low-arrival-rate local check, not a TP4 or prefill-throughput measurement; I have not validated a production scrape configuration. I would not infer a speedup from the small median differences or compare absolute timings causally with the older runtime.

Lewis-panda avatar Nov 18 '26 08:11 Lewis-panda