Skip to content

Add sglang.bench_latency for offline benchmark - #564

Merged
merrymercy merged 8 commits into
mainfrom
fix-micro-bench
Jun 25, 2024
Merged

merrymercy merged 8 commits into
mainfrom
fix-micro-bench

Conversation

@merrymercy

@merrymercy merrymercy commented Jun 25, 2024 •

Copy link
Copy Markdown
Collaborator
  • Add sglang/bench_latency.py. It is a very convenient utility for offline test.

Usage (latency test):

>>> python -m sglang.bench_latency --model-path meta-llama/Meta-Llama-3-8B-Instruct --load-format dummy --tp 2

Prefill. latency:  5.021 ms, throughput:    203.93 token/s
Decode.  latency:  0.331 ms, throughput:      3.02 token/s
Decode.  latency:  0.010 ms, throughput:    102.95 token/s
Decode.  latency:  0.009 ms, throughput:    107.55 token/s
Decode.  latency:  0.009 ms, throughput:    107.70 token/s
Prefill. latency:  0.019 ms, throughput:  52553.25 token/s
Decode.  latency:  0.009 ms, throughput:    108.23 token/s
Decode.  latency:  0.012 ms, throughput:     84.28 token/s
Decode.  latency:  0.009 ms, throughput:    108.52 token/s
Decode.  latency:  0.009 ms, throughput:    108.31 token/s

Usage (correctness test):

>>> python -m sglang.bench_latency --model-path TinyLlama/TinyLlama-1.1B-Chat-v0.4 --correct

prefill logits (first half) tensor([[-10.0312,  -9.5000,   0.8936,  ...,  -4.9414,  -3.2402,  -3.3633],
        [-10.0312,  -9.5000,   0.8936,  ...,  -4.9414,  -3.2402,  -3.3633],
        [ -9.1875, -10.2500,   2.7109,  ...,  -4.3359,  -4.0664,  -4.1328]],
       device='cuda:0', dtype=torch.float16)
prefill logits (final) tensor([[-8.3203, -7.1211,  3.3379,  ..., -4.9570, -4.1328, -3.4141],
        [-8.9062, -9.0156,  4.1445,  ..., -4.9922, -4.4961, -4.0742],
        [-9.6328, -9.0547,  4.0117,  ..., -5.3047, -4.7148, -4.4609]],
       device='cuda:0', dtype=torch.float16)
<s> The capital of France is.
The capital of the United States
<s> The capital of the United Kindom is.
The capital of the United Kingdom
<s> Today is a sunny day and I like go for a walk in the park.
  • Remove all other deprecated low-level API test files

@merrymercy merrymercy changed the title Fix bench_llama_low_api.py ADD bench_low_api.py Jun 25, 2024
@merrymercy merrymercy changed the title ADD bench_low_api.py Add bench_low_api.py Jun 25, 2024
@merrymercy merrymercy changed the title Add bench_low_api.py Add sglang.bench_latency Jun 25, 2024
@merrymercy merrymercy changed the title Add sglang.bench_latency Add sglang.bench_latency for offline benchmark Jun 25, 2024
@merrymercy
merrymercy merged commit eb1ae6a into main Jun 25, 2024
@merrymercy
merrymercy deleted the fix-micro-bench branch June 25, 2024 10:38
timethink pushed a commit to timethink/sglang that referenced this pull request Mar 9, 2025
vschandramourya pushed a commit to vschandramourya/sglang that referenced this pull request Feb 3, 2026
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
hzwzwzw pushed a commit to hzwzwzw/sglang that referenced this pull request Jul 2, 2026
hzwzwzw added a commit to hzwzwzw/sglang that referenced this pull request Jul 2, 2026
…-project#601 and sgl-project#628

Merge target: d958a63 "Return bad request for malformed DSV4 tool
arguments (sgl-project#602)". Excludes b4de164 (sgl-project#601 "Fix DSV4 C128 state
mapping lifecycle") and f59f166 (sgl-project#628 "Sync clean SM90 FP8+FP4
MegaMoE from main") per user instruction.

Brings in 13 upstream commits including:
- 3e31718 [HiCache] DeepSeek-V4 host-mem L2 + NVMe/disk L3 (sgl-project#564)
- 6dddb6d Fix DSv4 draft extend replay forward batch (sgl-project#569)
- 9d212a9 add observability (sgl-project#570)
- 104a38d Bytedance/deepseek v4 fix draft extend padding (sgl-project#573)
- d958a63 Return bad request for malformed DSV4 tool arguments (sgl-project#602)
- 8 docker/codex build hardening commits

Conflict resolutions (all 8 files stability-critical, memory-related):

1. tree_component.py / full_component.py / swa_component.py / mamba_component.py
   -- commit_hicache_transfer signature: keep HEAD's typed
   (insert_result, pool_storage_result) kwargs. Callers in
   unified_radix_cache.py explicitly pass these; their **kw variant
   is strictly a superset but less safe.
   Also drop their side's manual `kw.get(...)` extraction in mamba
   PREFETCH branch since the params are now directly bound.

2. hybrid_cache_controller.py -- extra_host_mem_release_queues type
   annotation: keep HEAD's Queue[torch.Tensor] (more precise).

3. swa_memory_pool.py -- their side added a full duplicate
   SWATokenToKVPoolAllocator class inline in this file, but our fork
   moved the class to allocator/swa.py in an earlier refactor. Drop
   their duplicate; instead apply sgl-project#573's free_swa fix (guard against
   negative sentinels and out-of-range indices, expand page-aligned
   free) directly to allocator/swa.py where the class actually lives.

4. hybrid_pool_assembler.py:
   - kvcache.compress_state_pools indexing: keep either form (addition
     is commutative); use HEAD's ordering for local consistency.
   - C128 state pool registration: keep HEAD's explicit non-registration
     with the "C128 State pool intentionally not registered" comment.
     Our HEAD's upstream sgl-project#27293 deliberately opted out; their side (from
     before sgl-project#601) still registers it. Silently reintroducing the pool
     would regress the fix and pressure host memory.
   - attach_hybrid_pool_to_unified_cache body: keep HEAD's
     _select_strategy(...).build() dispatch (from upstream sgl-project#26295)
     over their 245-line inline if-elif chain. Our _DeepSeekV4Strategy
     already handles the deepseek_v4 stack; the strategy signature
     already accepts storage_backend / storage_extra_config /
     storage_prefetch_threshold.

5. unified_radix_cache.py (24 conflicts) -- keep HEAD wholesale:
   - HEAD has 10 methods theirs lacks (all from upstream sgl-project#26881,
     sgl-project#27285, sgl-project#27391, sgl-project#27489, sgl-project#27554, sgl-project#27655 L3 support + our PR sgl-project#27010
     port: prefetch_sync_thread, ack-driven sync, handle_prefetch_result,
     _drain_async_work, _finish_write_through_ack, etc.)
   - Their only extra method (terminate_prefetch(rid)) was deliberately
     removed by our PR sgl-project#27010 port.
   - HEAD's load_back_threshold=10 matches hi_mamba_radix_cache and
     hiradix_cache (theirs=256 was an inconsistent local tuning).
   - HEAD passes total_len to InsertResult (dataclass field exists) and
     priority to UnifiedTreeNode (LRU correctness).
   - HEAD's write_backup early-returns on written==0 (upstream sgl-project#27108
     safety fix); theirs drops the check.
   - HEAD's _drain_queue is blocking with qsize MIN-reduce (our PR
     sgl-project#27010's lockstep drain); theirs is old get_nowait+Empty pattern
     that would desync PP/TP.
   - sgl-project#564's L2/L3 additions in this file are functionally covered by
     upstream sgl-project#26881 (already in HEAD via ep_main). No net feature
     loss from taking HEAD.

Verified: AST parse OK for all 9 mem_cache files, compileall exit=0
on managers + mem_cache trees.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
kenzhangwangshu added a commit to kenzhangwangshu/sglang that referenced this pull request Jul 17, 2026
Bump the mainline DeepEP pin from 9af0e0d (v1.2.1, 2025-09-15) to
567632d, the last commit before the EPv2 repo reorg (sgl-project#605). This picks
up deepseek-ai/DeepEP#458 (hidden-dim 3072 low-latency kernels), the
use_fabric buffer kwarg (sgl-project#217), and NVSHMEM 3.5 runtime fixes (sgl-project#564),
while keeping the pre-reorg layout the Dockerfile build steps expect.
Also updates the matching checkout in ci_install_deepep.sh.

Context: sgl-project#24502.
efschu added a commit to efschu/htsglang that referenced this pull request Aug 4, 2026
… unit

The reference generates a complete unit and only then emits it, so
time-to-first-audio equalled full generation time by construction: the field
session ea7531b498c6 waited 6866 ms and then received the whole utterance in a
199 ms burst. MEASURE_TTS_LATENCY.md attributed all of it -- ~74 decode steps
at 92.6 ms, against 79 ms of fixed cost -- and ranked incremental emission
first because codec decode is 36 ms and FLAT across a 6x range of length.

Audio is now taken out as codec frames are sampled. The reference offers no
streaming output at all and the two arguments that could carry one are
swallowed by the closed talker_kwargs dict literal, so the frames are taken
with a forward hook on the talker (hidden_states[-1] per step, prefill entry
dropped -- exactly what the reference itself assembles afterwards) and decoded
in growing prefixes through the reference's own speech_tokenizer.

WHEN emission may start is the whole problem. Generation is SLOWER than
playback -- RTF 1.158 idle, 1.256 with the 27B saturated -- so a stream that
starts at frame 1 is overtaken by its own playback and gaps before the end.
release_frame solves the inequality for the release point, sized against the
whole TURN rather than one unit (TurnPacing: the units are synthesized back to
back on one talker, so sizing per clause moves the gap to the seam instead of
removing it) and against a MEASURED real-time factor rather than a constant.

Two design decisions and what they cost:

* The sgl-project#564 re-draw and streaming are mutually exclusive, because a re-draw can
  only replace audio nobody has heard. The line is drawn where the bar draws
  it: a unit whose whole generation fits the 2361 ms the bar leaves is
  generated whole and keeps the re-draw -- which covers "Gracias.", the clause
  the runaway was observed on -- and everything above it is streamed and gives
  it up. For the runaway shape that ends in digital silence this costs
  nothing, since the prospective trim never puts that tail on the wire; for
  the shape that babbles, the listener now hears it until step_budget stops
  the unit where a re-draw would have replaced it.
* Past the crossover the two halves of the bar cannot both hold. The pre-roll
  is capped at the budget and the projected shortfall is logged: the start
  time is the half the user stated as a number.

The prefix decode is NOT byte-identical to the one-shot decode, and the reason
is measured rather than assumed. It was built on the argument that the decoder
is causal; probe_prefix_decode.py falsified that (disagreement starts at sample
ZERO, so no holdback removes it) and probe_decode_strategies.py located the
cause: 25 frames of context reproduce the shipped waveform at 25.2 dB and 50
frames at 39.4 dB, i.e. the decoder reaches 25-50 frames FORWARD in time.
Exactness would mean withholding four seconds of audio. What ships is the best
any incremental emitter can do -- the whole prefix, lacking only audio that
does not exist yet -- at 39.4 dB, with chunk seams of 0.0427 against the
one-shot decode's own 0.0411 at the same sample positions.

Test results, RTX 5090 selected by NVML UUID, live translator and the 27B
resident and untouched throughout, arms interleaved and seeded so both decode
the identical token sequence:

* time-to-first-audio, median of 3, burst -> streamed:
    field turn (58 chars)   5252 ms -> 2021 ms
    long turn (112 chars)  11249 ms -> 2341 ms
    short turn (10 chars)   2479 ms -> 2557 ms  (whole-unit path, unchanged)
  The short pair is the A-versus-A floor: both arms take the identical code
  path, and they differ by 8-80 ms (0.7-3.2 %). The field improvement is ~40x
  that.
* gapless, emission timestamps replayed against a playback clock and sampled
  at the trough BEFORE each chunk lands: worst buffer +0.400 / +0.034 /
  +0.039 s on the field turn. The long turn is beyond the crossover and
  underruns by design, with the cap warning naming the shortfall.
* what the wire carried equals what the unit returned, exactly (0.0 on every
  arm), so the audio recorded for a turn is the audio the listener heard.
* a full decode of the tapped frames equals the reference's own decode of the
  same generation, exactly (0.0 across nine seeded pairs) -- which is also
  what rules out the tap perturbing the generation.
* the re-draw conflict, forced by driving step_budget_factor below 1.0 rather
  than waiting for a stochastic runaway: with the budget above the release
  point, audio is already sent and the unit is truncated instead of re-drawn
  (1 draw, 9 chunks, every sent sample present in the result); with it below,
  nothing has been sent and the re-draw still fires.
* 641 tests pass (test/registered/translator), 28 of them new. ruff clean.

The first probe run found two defects in this change and both are fixed here:
the pre-roll was sized on a rate measured before any decode had run, which is
structurally optimistic and underran by 0.39-1.57 s on every streamed arm; and
the text-duration fit ran short by up to 48 % on real draws.

Client-side blast radius is nil by construction: 0.4 s is exactly 5 codec
frames, so a unit still arrives as the same number of turn.audio buffers and
every per-buffer counter in the playback hold keeps its baseline.

Per-turn seams left for the message-level controls that follow. Nothing new is
wired: `playback.stop` stays global. What changes is that stopping ONE turn is
now a narrowing of the existing path rather than a second mechanism. TurnPacing
carries `turn_id`, `target` and `generation`, so a synthesis in flight can be
identified and a re-synthesis of the same turn is distinguishable from its
original; the emitter reads a `cancelled` flag before every chunk, so audio can
be stopped at the source without cancelling a talker thread that cannot be
cancelled anyway. `started` is the single point of no return, on the turn and
not the unit, and both the re-draw and any future replacement read that one
flag. Two places that would have misread a stop as a delivery failure -- the
completeness check and the fallback that sends a finished waveform when nothing
streamed -- are guarded now, which is cheap before the feature exists and a
defect hunt afterwards. Nothing in the synthesizer is keyed by turn, and a test
pins that so a later registry cannot quietly make re-synthesis inexpressible.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant