Skip to content

[Feature] Support fp8 e5m2 kv cache with flashinfer - #1204

Merged
merrymercy merged 7 commits into
sgl-project:mainfrom
ispobock:fp8_kv_cache
Aug 26, 2024
Merged

merrymercy merged 7 commits into
sgl-project:mainfrom
ispobock:fp8_kv_cache

Conversation

@ispobock

@ispobock ispobock commented Aug 25, 2024 •

Copy link
Copy Markdown
Collaborator

Motivation

Support fp8 e5m2 kv cache with flashinfer.

Usage

Add --kv-cache-dtype fp8_e5m2 to enable this feature. Currently it only works when flashinfer is not disabled.

Performance & Accuracy

Tested with llama2-13b-chat on A100, the throughput increased by 17.8% without accuracy degradation.

Enable fp8_e5m2 kv cache Throughput MMLU (nsub=10) Avg Accuracy gsm8k Accuracy
N 7.04 req/s 0.487 0.340
Y 8.30 req/s 0.488 0.334
Reproduce
# w/o fp8_e5m2 kv cache
python3 -m sglang.launch_server --model-path meta-llama/Llama-2-13b-chat-hf --port 30000 --trust-remote-code --disable-radix-cache --tp=1
# w/ fp8_e5m2 kv cache
python3 -m sglang.launch_server --model-path meta-llama/Llama-2-13b-chat-hf --port 30000 --trust-remote-code --disable-radix-cache --tp=1 --kv-cache-dtype fp8_e5m2

# benchmark
python3 -m sglang.bench_serving --backend sglang --tokenizer meta-llama/Llama-2-13b-chat-hf  --dataset-path ShareGPT_V3_unfiltered_cleaned_split.json --num-prompts 1000 --request-rate 128

# evaluation
python3 benchmark/mmlu/bench_sglang.py --nsub 10
python3 benchmark/gsm8k/bench_sglang.py --num-questions 1319

The performance boost is model dependent. llama3-8b was also tested, but the performance was not improved.

@zhyncs zhyncs self-assigned this Aug 25, 2024
@zhyncs

zhyncs commented Aug 25, 2024

Copy link
Copy Markdown
Contributor

Nice work! I'll review it asap. May we also support FP8 E4M3?

@zhyncs
zhyncs requested a review from yzh119 August 25, 2024 08:25
@zhyncs zhyncs added the feature label Aug 25, 2024
@zhyncs zhyncs mentioned this pull request Aug 25, 2024
15 of 29 tasks
@ispobock

Copy link
Copy Markdown
Collaborator Author

May we also support FP8 E4M3?

FP8 E4M3 needs scale factor and calibration. We may add it in the future.

if self.server_args.kv_cache_dtype == "auto":
self.kv_cache_dtype = self.dtype
elif self.server_args.kv_cache_dtype == "fp8_e5m2":
if self.server_args.disable_flashinfer or self.server_args.enable_mla:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Currently, only FlashInfer is supported and not Triton, due to the issue of insufficient smem. This needs to be fixed in another PR.

if cache_v.dtype != self.dtype:
cache_v = cache_v.to(self.dtype)
if self.store_dtype != self.dtype:
self.k_buffer[layer_id][loc] = cache_k.view(self.store_dtype)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

workaround for float8_e5m2

Store as torch.uint8 because Tensor index_put is not implemented for torch.float8_e5m2

Co-authored-by: Lianmin Zheng <[email protected]>
@zhyncs
zhyncs enabled auto-merge (squash) August 25, 2024 17:37
@merrymercy merrymercy changed the title Support fp8 e5m2 kv cache with flashinfer [Feature] Support fp8 e5m2 kv cache with flashinfer Aug 25, 2024
@qeternity

Copy link
Copy Markdown
Contributor

Sorry to dig this up but - are we suggesting that fp8 kv cache increased accuracy in both mmlu and gsm8k? Are we sure we don't have those values in the table reversed?

@ispobock

ispobock commented Oct 12, 2024 •

Copy link
Copy Markdown
Collaborator Author

@qeternity In the previous evaluation, I tested gsm8k with 200 questions (default setting in the benchmark script), so the result may not be reliable enough. I just test all the datasets and update the result in the table.

timethink pushed a commit to timethink/sglang that referenced this pull request Mar 9, 2025
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 4, 2026
…y hangs the ones that did not

D1 -- level_kv_backing_to_group read backed_rows() and live_floor_rows()
BEFORE reduce_fn, and returned outright when this rank had no relief object.
Either exit walks on while the peers block for ever inside the MIN all-reduce,
and neither raises anywhere: the leaver did not raise and the peers are stuck
in a collective, not in Python. It is the one failure in the no-return region
that leaves no traceback on any rank.

Reachable, not hypothetical: the relief is installed rank-locally under a
try/except that sets it to None on ANY per-device failure, and this rig is
heterogeneous (31800/18800/19800 MiB per rank), so "one card failed, two did
not" is the ordinary shape of that except.

The fix copies the sibling collective_kv_backing_relief in shape ("Abstain --
but still reduce, because a rank that returns early here hangs the ones that
did not"): keep the reduce_fn-is-None return (no channel, nobody blocked),
drop the relief-is-None return, move both rank-local reads under their own
except that abstains instead of leaving, and enter reduce_fn unconditionally
with kbr._UNBOUNDED_ROWS in all three slots -- the neutral this same MIN
channel already uses in ABSTAIN/SLOT_ABSTAIN, imported rather than restated.
The abstainer returns None: it agreed to nothing it can apply.
The except arm's text is corrected: its claim "a lost flip, never a
half-flipped group" was true of the post-reduce decline and exactly wrong for
the pre-reduce reads it used to catch.

D2 -- the pre-cutover mover loop (weights arena refill, GDN state leg; both
are _pre_cutover_fns, so both are covered) ran unwrapped inside the no-return
region. It never swallowed, and it still does not: what was missing was the
NAME. Extracted to run_pre_cutover_movers, which records the leg before it
raises, logs which leg failed and that it failed after the region closed, and
re-raises as SeamMoverError chained from the original. A failed leg is not
census-marked and the legs behind it do not run over a half-written arena.

RED FIRST (parent 1559bda, hermetic, CVD=""):
  test_seam_abstain_into_reduction_1204.py -> 7 failed, 2 passed.
  The D1 arm failed on "AssertionError: 3 != 2" -- two ranks entered the
  channel, three were supposed to.
  After: 9 passed.

MUTANTS (all killed):
  M1 DANGEROUS abstainer sends [0,0,0]            -> test_red_c (neutrality)
  M2 DANGEROUS abstainer sends [n,-n,-n]          -> test_red_c (neutrality)
  M3          restore the relief-is-None return   -> test_red_a (arrival)
  M4 DANGEROUS D2 swallows and continues          -> test_red_a/b/c of D2
  M5          census marked before the leg ran    -> test_green_order, red_b

VERIFIED: touched file + immediate siblings, 57 passed / 11 failed; the same
11 fail at the parent with the same AttributeError ('PhaseFlipRuntime' object
has no attribute '_rank') in test_seam_shrink_834.py -- pre-existing, parity
held. ruff clean on all three files. black delta of the new hunk removed (both
managers files already fail black at the parent). AST check: no bare loop over
_pre_cutover_fns remains, the call sits inside _execute_body, the helper's
mover arm ends in a raise.

NOT VERIFIED: no boot, no GPU, no metal. The trigger for either site remains
unwitnessed in any boot log -- this closes the site, it does not prove the
symptom.

PREMISE FALSIFIED, and it is why D2 stops at a rank-local death: the brief
asked for a failure flag reduced into the payload at level_kv_backing_to_group.
There is no collective between the mover loop and self._cutover_fn to carry
one -- the seam's consensus MIN is upstream of the no-return point,
_reconcile_trees_if_diverged only reads a verdict that reduction already
produced, and the levelling's reduce runs on the tp->pp POST-cutover hook. A
flag reduced there announces the failure after the cutover it was meant to
prevent, on one leg of two. Opening a new collective inside the no-return
region is the 2026-08-08 boots 9/10 wedge shape. So the rank dies loudly and
by name instead (raenge-nie-uneins-crash-stop).
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 4, 2026
…ee adversarial lenses found in the six cuts

WHAT WAS RED, and every finding was re-verified at the tree before it was
acted on. Two of the eleven reported were REFUTED and are named at the end.

1. sgl-project#1202 added `mbs` to the residency AUTHORITY and not to the retirer.
   `_live_reqs` walks `mbs`; `consume_retracted_from_live_universe` did not.
   That is the W30 asymmetry re-opened, and it is the W27 death: the release
   frees a request the authority then re-enumerates, and
   `resident_mamba_slots` (gdn_flip_mover.py:620) raises KvReshardError on a
   live request with no mamba slot -- inside the no-return region, where the
   only outcome is a dead rank. The mbs-only shape is ordinary, not exotic:
   under event_loop_pp a freshly planned prefill batch sits in `mbs[slot]`
   while `running_mbs[slot]` holds the decode set.
   RED: the property test "authority and retirer walk the same containers"
   reported authority-only = ['mbs']; the concrete test read
   "0 != 1 : the mbs route retired no reference".
   Pinned as a PROPERTY over the two walks, so the next route added cannot
   reintroduce it. The stale present-tense collateral at
   scheduler_pp_mixin.py:5121 ("_live_reqs does NOT enumerate mbs", dated
   2026-09-04) is rewritten as the dated fact it now is.

2. sgl-project#1203 A5 spent three ESCALATION budgets in the group's abandon currency.
   A5's premise is right and is kept: a rank-local counter that zeroes itself
   when this rank's own objection clears can never reach its limit while
   ranks take turns objecting. But `flip_host_headroom_verdict` and
   `flip_seam_budget_verdict` do not merely stop deferring at the limit --
   they return (allow=True, escalated=True), "PROCEEDING WITH EYES OPEN"
   under a failed sgl-project#721 host floor -- and the writeback arm proceeds with an
   incomplete sgl-project#703 fence. `_seam_abandons_in_a_row` is incremented on EVERY
   reduced-fit abandon or frame divergence, so three unrelated abandons
   disarmed all three guards and the next GENUINE shortfall escalated on its
   first firing, having deferred zero times. A bound may be widened to the
   group's currency; an escalation that permits the hazard may not.
   REPAIR: each guard is bounded by its own count again, and that count is
   refunded ONLY by a completed flip (beside the abandon book, whose own
   comment already states the rule) or by the guard's own escalation. The
   whole reset policy is `flip_defer_budget_after`, one pure function, so the
   three copies cannot drift again.
   RED: 8 of 10 A5 tests failed at the parent.
   Three instruments that named the wrong counter are corrected with it:
   "consecutive" becomes "in this abandon run", and the host-RAM defer is
   booked BEFORE its own log line instead of after.

3. sgl-project#1204's abstain discarded a term the rank had successfully read. Both
   reads shared one `try`, so a rank whose `backed_rows()` succeeded and whose
   `live_floor_rows()` then raised contributed `_UNBOUNDED_ROWS` in slot 0 --
   the MIN identity, i.e. "I am not the poorest". Slot 0's MIN becomes the
   level the peers cap to and the ceiling `book_deferred_grow` clamps to, so
   erasing a poor rank makes the group agree an id level it cannot map, which
   `backed_rows`' docstring calls a cudaErrorIllegalAddress that kills every
   rank. The hang the commit removed would have been traded for a wrong group
   answer -- the corrupting direction bought to avoid the refusing one.
   REPAIR: abstain PER SLOT. Each slot carries this rank's own measurement or
   that slot's neutral, unchanged for a wholly unreadable relief.
   RED: "30 != 1099511627776".

4. sgl-project#1205's `seam_refused` measured a population its label does not name --
   the sgl-project#1205 defect class, committed inside the sgl-project#1205 fix. The fence read
   `seam_refusals()` with NO direction, summing "load" refusals raised on the
   controller's own background threads while the fence runs, and printed the
   delta as "of refused_silently, the share the FLIP SEAM refused".
   REPAIR: `seam_refusals("write")`, and the log line and the field comment
   now say what it is: process-wide write-direction refusals during the fence,
   not a subset of `refused_silently` and not per-node (consume_gate refuses a
   whole queue and counts one).
   RED: "1 != 3" when the direction-less read is put back.

5. `assert_future_map_identity` was REACHED and CANNOT-FAIL. Measured: four
   combinations of (algo NONE|EAGLE) x (pool pp|tp), ZERO fires.
   `create_future_map` passes `self` as `spec_algo` and the scheduler's pool
   straight into `ConfidenceRelay`, so both stamp arms are construction
   invariants at a call site 57 lines after the rebuild; the two suite tests
   that are green hand-mutate a map no code path produces.
   REPAIR: the registry's obligation is "a probe proving the rebuild ran", so
   the probe now takes `previous` -- the map held BEFORE the rebuild -- and
   refuses when the rebuild did not replace it. A memoised build, a deleted
   assignment or a rebuild moved out of the cutover all land there and none of
   them are visible to the stamp arms. The tautology is pinned as a fact so
   the green is not read as coverage.

6. MambaRadixCache got the sgl-project#1201 assertion but not the sgl-project#1201 fix. It caches
   `req_to_token_pool` as a plain attribute and has no `bind_req_pool_owner`,
   so `_restamp_phase_handles`' hasattr guard skipped it and the handle stayed
   on the outgoing pool -- and `assert_req_pool_identity`, added to both
   classes, then raises ReqPoolRebindRefused at the END of every cutover.
   Reachable: registry.py hands back this class for a hybrid-SSM model WITHOUT
   hierarchical cache. The boot went from flipping wrongly to not flipping.
   REPAIR: the same owner property and bind hook UnifiedRadixCache got.

7. The sgl-project#1203 A1 group vote moved a non-pure function onto a new cadence.
   `seam_transport_premise_holds_locally` writes the edge-triggered
   `_seam_premise_refused_announced` latch and emits SEAM TRANSPORT REFUSED;
   the vote runs once per loop iteration while the consumer returns at
   `_active_phase != PHASE_TP` before it asks. The latch was therefore set in
   the PP phase, swallowing the gate's own first engagement in TP.
   REPAIR: `announce=False` for the vote; the gate's own read still announces.

Also: the anchor at overlap_utils.py:81-83 had drifted onto the line that
REFUTES its sentence -- scheduler.py:13174-13177 is now the overlap call
inside `if self.enable_overlap:`, while the non-overlap spec branch is the
sibling `elif not batch.spec_algorithm.is_none():` arm. The claim is true; the
number sent the next reader to the wrong branch. Named by branch, no number.

WHAT KILLED WHICH MUTANT (planted in place, restored by sha256):
  M1 retirer over-clears (frees a row a live req owns, the corrupting
     direction) -> test_an_mbs_only_resident_is_retired_by_the_retraction
  M2 host bound back on the group abandon book (disarms sgl-project#721)
     -> test_the_host_headroom_bound_reads_its_own_defer_count
  M3 a cleared vote refunds its own budget (the A5 wedge)
     -> test_this_rank_clearing_does_not_refund_the_budget
      + test_a_taking_turns_run_still_reaches_the_limit
  M4 refund moved back into the gate's cleared-vote branch
     -> test_a_completed_flip_returns_every_budget_beside_the_abandon_book
  M5 sgl-project#1204 discards a measured backing again (claims not-poorest, the
     fleet-death direction)
     -> test_a_readable_backing_reaches_the_group_min
  M6 MambaRadixCache loses the rebind hook
     -> test_both_classes_expose_the_rebind_hook
      + test_the_handle_follows_the_owner_and_falls_back_without_one
  M7 the seam stops handing the probe the outgoing map
     -> test_the_seam_hands_the_probe_the_outgoing_map
  M8 the A1 vote announces again
     -> test_the_vote_leaves_the_announcement_latch_alone
8 planted, 8 killed, 0 survived.

VERIFIED: 146 passed + 7 subtests over the six touched test files plus
test_1157_seam_witness.py and test_seam_census_double_905.py (the joint pin
over both sgl-project#1202 functions), hermetic, CUDA_VISIBLE_DEVICES="" with the serving
venv. Import smoke over all seven edited modules. ruff parity with the parent
on the touched files: 31 findings both sides, all pre-existing.

NOT VERIFIED: nothing on metal. No boot, no GPU claimed, no collective. The
sgl-project#1204 and A5 repairs are DESK-PROVEN only -- neither has run against a real
reduce or a real host-RAM shortfall.

REFUTED, and left untouched: (a) `assert_req_pool_identity`'s tree-cache arm
is not decorative -- it is a construction invariant for UnifiedRadixCache
BECAUSE the owner property is the fix there, and a live check for every other
holder class, which is exactly what caught finding 6; (b) `seam_refused` was
already read as a delta across the fence run (hicache_flip_writeback.py:700),
not as an absolute, so only its direction and its label were wrong.
xdtbynd pushed a commit to xdtbynd/sglang that referenced this pull request Sep 17, 2026
Add --expert-balancedness-report-mode, --enable-session-radix-cache, --model-checksum, --moe-dp-size,--pp-size/--pipeline-parallel-size parameter testcases
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants