Skip to content

Add cache metrics - #119

Merged
merrymercy merged 3 commits into
mainfrom
cody/metric
Jan 31, 2024
Merged

merrymercy merged 3 commits into
mainfrom
cody/metric

Conversation

@comaniac

Copy link
Copy Markdown
Contributor

This PR introduces several cache metrics for better benchmarking and analysis.

  • Tree cache hit rate: The accumulated cached_token / total_token ratio.
  • FSM cache hit rate: The accumulated init_fsm_cache / total_query ratio.
  • FSM cache average initialization time: The average RegexFSM initialization time.

The log now becomes (a bit long...)

new fill batch. #seq: 1. #cached_token: 2510. #new_token: 18. tree_cache_hit_rate: 62.18%. fsm_cache_hit_rate: 33.33%. fsm_cache_avg_init_time: 15.73s. #remaining_req: 0. #running_req: 0

@comaniac

comaniac commented Jan 30, 2024 •

Copy link
Copy Markdown
Contributor Author

New changes:

  • Unify in-memory cache interface so that both FSMCache and FastForwardCache could have the same metrics.
  • Put FSMCache and FFCache metrics to logger.debug so that users could use --log-level debug to enable it.
  • Temporary fix Crash in tokenize_fast_forward #115 so that it works for Llama2, Qwen and Falcon tokenizers at least.

@merrymercy
merrymercy merged commit 71b54ee into main Jan 31, 2024
@merrymercy
merrymercy deleted the cody/metric branch January 31, 2024 06:13
timethink pushed a commit to timethink/sglang that referenced this pull request Mar 9, 2025
@xihuai18 xihuai18 mentioned this pull request Mar 20, 2025
3 of 5 tasks
NorthmanPKU pushed a commit to NorthmanPKU/sglang that referenced this pull request May 16, 2025
… faster (sgl-project#119)

* Support Parallel transpile

* fix pytest

* fix typo
pi314ever pushed a commit to pi314ever/sglang that referenced this pull request Aug 14, 2025
efschu added a commit to efschu/htsglang that referenced this pull request Jul 26, 2026
…ccounted quantity

The offload frees expert weight VRAM at two different moments -- the sgl-project#123
load-time presplit (GPTQ/AWQ-marlin, param swapped for a 0-row placeholder)
and the split-here branch of MoEExpertOffloadCache.install() (fp8/triton) --
and neither said how much. ResidencyStats counts fetches and hits, never
bytes, so the size of the reclaim the KV pool is supposed to inherit was not
a number anywhere in the process.

Add a per-rank tally: expert_offload_released_device_bytes() is the pure
(experts - buffer_slots) * row_bytes function, and record/totals/reset wrap
a module-level accumulator that each release site bumps exactly once per
layer. The presplit branch of install() deliberately does not record -- the
presplit already did, and counting it twice would double-report the reclaim.

Also declare SGLANG_MOE_OFFLOAD_KV_REGAIN (default on). It is additionally
gated on SGLANG_MOE_RESIDENT_EXPERT_FRACTION < 1.0 everywhere it is read, so
with the offload off it changes nothing.

Purely additive; no existing line altered. Tests in sgl-project#119.2.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 26, 2026
…ffload freed

The reclaim needs no second sizing path. _profile_available_bytes derives the
KV budget from a live free-memory reading taken after the weights are
resident, so VRAM the offload hands back is already inside it -- provided the
release has happened, on every rank, before anyone measures. sgl-project#123's eager
install (right after load_model, ahead of pool sizing) supplies the first
half. What was missing is everything that makes that hold rather than happen
to hold:

1. Ordering invariant. A FusedMoE layer still waiting to install when the
   pool is sized would release its experts on its first forward, i.e. after
   sizing: the pool is then sized against the pre-offload footprint and later
   collides with the resident buffers. That was the sgl-project#77 "known limitation",
   and nothing prevented a refactor from restoring it silently.
   _assert_expert_offload_installed makes it a loud rank-local ValueError,
   matching the rank-local budget errors already in this function. Weightless
   workers (meta model, no expert weights) are skipped.

2. Group-ordered release. get_available_gpu_memory reads mem_get_info(),
   which is driver-level and therefore sees co-located siblings, while the
   caching allocator only returns freed blocks at empty_cache(). Every rank
   empties its own cache inside its own reading, unsynchronized -- so a rank
   that reads early counts a sibling's already-released expert weights as
   still occupied. Below the offload that skew was small. At f=0.25 on the
   122B run it is the whole reclaim (~18 GiB on the shared card), landing in
   the co-location and min-reduce terms as pure noise.
   _expert_offload_release_sync makes it collect -> empty_cache -> barrier,
   so no rank measures before every rank has released.

3. Rank-uniform verdict. The reclaim changes the pool the whole TP group
   shares, so "is it present" is a MIN over the group, not a rank-local
   answer: a rank that released nothing (MoE-free shard, failed install
   falling back to fully-resident) makes the group take the plain path
   instead of half the ranks synchronizing while the other half measures
   unsynchronized. Rank-local test first, then the collective -- and both
   gate terms are env vars, hence world-uniform, so the collective can never
   be entered by a subset.

4. Accounting. [offload-kv-regain] logs the released device/host bytes next
   to the KV budget they are part of, so the win is readable from a boot log
   and a regression shows up as a drop there instead of an unexplained
   smaller pool.

No new budget term, so the sgl-project#68 graph-capture reserve is untouched: the
reclaim arrives as free bytes and is spent net of the same reserves
(derived_rank_auto_reserve_mib / reserve_for_graph_mb, both folded in
earlier) as any other free byte.

Tests: test/registered/unit/model_executor/test_expert_offload_kv_regain.py,
27 CPU cases, no GPU -- collectives and memory readings mocked.

  green  27/27 after the change
  red    before it: with the ordering hook removed but the new symbols kept,
         test_release_precedes_the_measurement fails
         (['read'] != ['all_reduce','collect','empty','barrier','read'])
         and test_pending_install_aborts_before_any_measurement fails
         ("ValueError not raised")

  test_reclaim_lands_one_to_one_and_spares_the_graph_reserve passes on both
  sides, as it should: that invariant is sgl-project#123's, and this commit only pins it
  down so it cannot drift.

Regression, same interpreter/venv:
  unit/distributed/test_uneven_tp_memory.py       33/33 OK
  unit/server_args/test_uneven_tp_args.py         71/71 OK
  unit/server_args/test_rank_kv_ratio_args.py     26/26 OK
  unit/server_args/test_swa_pool_sizing.py        15/15 OK
  tests/moe_offload/test_planner.py               18/18 OK
  tests/moe_offload/test_capturable_planner.py    27/27 OK
  unit/model_executor/test_pool_configurator.py   25 errors -- pre-existing,
    identical error set before and after this change (diffed); unrelated
    cause (stub ModelRunner lacks swa_pool_sizing).

Default path: the diff is additive only, and both gates are off without
SGLANG_MOE_RESIDENT_EXPERT_FRACTION < 1.0, so the no-offload sizing path
takes no extra collective and no extra cache operation
(test_default_path_untouched asserts the call log is exactly ['read']).

GPU validation still outstanding; no GPU on this lane.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 27, 2026
Records merges 2-10 with per-step semantic pre-checks, the sgl-project#189 x sgl-project#192 conflict
resolution and its per-card verification, the two deliberately skipped branches
(sgl-project#143 Gate 4 never measured, sgl-project#119 needs a 122B A/B that did not fit), and the
failure-set diff: 36 pre-existing failures at 9b142ce -> 11 at the merge tip,
no new ones, with the 25-case test_pool_configurator red repaired by sgl-project#96.
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.

2 participants