Skip to content

[Feat] Add window attention for gemma-2 - #1056

Merged
Ying1123 merged 4 commits into
mainfrom
ying-window
Aug 14, 2024
Merged

Ying1123 merged 4 commits into
mainfrom
ying-window

Conversation

@Ying1123

@Ying1123 Ying1123 commented Aug 12, 2024 •

Copy link
Copy Markdown
Contributor

DO NOT turn on auto-merge.
I'll merge it manually.

Comment thread python/sglang/srt/server_args.py Resolved
@Ying1123 Ying1123 changed the title feat: Add window attention for gemma-2 [Feat] Add window attention for gemma-2 Aug 12, 2024
@zhyncs

zhyncs commented Aug 12, 2024

Copy link
Copy Markdown
Contributor

@Ying1123 We can temporarily change DEFAULT_MODEL_NAME_FOR_TEST to gemma to trigger the CI test, and then change it back to Llama after verification.

@Ying1123
Ying1123 force-pushed the ying-window branch 3 times, most recently from 7ac08ad to 0ad6781 Compare August 12, 2024 12:38
@zhyncs zhyncs added the enhancement New feature or request label Aug 12, 2024

@NihalPotdar NihalPotdar left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I tried out the engine with the gemma-2-2b, 9b, and 27b models, and looks good. Left some quick comments. Overall lgtm!

@Ying1123
Ying1123 force-pushed the ying-window branch 7 times, most recently from 06d3450 to f0f9941 Compare August 13, 2024 22:04
@Ying1123
Ying1123 force-pushed the ying-window branch 2 times, most recently from 224b293 to 749a8ff Compare August 13, 2024 22:41
Comment thread python/sglang/srt/server_args.py Resolved
@Ying1123
Ying1123 merged commit 0909bb0 into main Aug 14, 2024
@Ying1123
Ying1123 deleted the ying-window branch August 14, 2024 00:01
Comment thread python/sglang/srt/models/gemma2.py Resolved
self.disable_radix_cache = True
self.disable_regex_jump_forward = True
self.disable_flashinfer = False
self.disable_cuda_graph = True

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

cuda graph should be turned on

Comment thread python/sglang/test/long_prompt Resolved
@Ying1123

Copy link
Copy Markdown
Contributor Author

Additional comments addressed in #1090

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 Aug 31, 2026
… counting forwards

A rank loading a Triton module needs the device; the peers' barlink spin
kernels saturate it while they wait for that rank in a collective. Closed
cycle, group wedged. Two fully captured specimens:

* BOOT 22: `_dcp_write_scatter`, cold, on the FIRST FORWARD AFTER A CUTOVER.
  #1033c answered it by arming `cold_build_window` for the first
  `_post_cutover_build_batches = 8` forwards after each cutover.
* BOOT 25: `l2norm_fwd`, cold, on an ORDINARY forward, on TWO ranks at once,
  ~90 s into load and 57 clean cutovers later -- far outside that counter.
  py-spy, two samples per rank, identical frames both times.

#1033c is not wrong. It is BOUNDED BY A COUNT, and a first-loader whose first
call is late is outside any count. `devtools/CENSUS_1033c_first_loaders.md`
predicted exactly this: rows 7 and 8 UNVERIFIED, the table calling itself a
LOWER BOUND. An enumeration is not completed by adding rows to it, and a second
counter would inherit the defect. So this cuts the class instead.

THE CHOKEPOINT IS ONE FUNCTION. `CompiledKernel._init_handles` is the only
place a kernel's module can come into existence -- `load_binary`
(`cuModuleLoadData`) is called there and nowhere else, and Triton's own
`kernel_load_start_hook`/`kernel_load_end_hook` bracket precisely that call,
which is what identifies it as the intended extension point. Wrapping it covers
EVERY future first-loader by construction: no enumeration, no census to keep
current, no counter to tune. Since sgl-project#615 `cold_build_window` publishes at every
call site, so the window opened here is group-visible with no further plumbing.

WHY THE METHOD AND NOT THOSE HOOKS -- the one real trade-off, decided on
exception safety. The END hook runs only on the success path, so a load that
RAISES would leave the window open for the life of the process and stretch
every collective deadline permanently. A `with` block closes on both paths, and
`cold_build_window` is documented re-entrant and exception-safe. The hooks stay
untouched and available.

STEADY STATE IS ONE ATTRIBUTE CHECK. `_init_handles` already opens with
`if self.module is not None: return`. The wrapper asks that FIRST and delegates
untouched, so a warm launch never constructs the window. That early return is
the zero-cost precondition, so it is ASSERTED against the installed Triton
rather than assumed: if a future build drops it, the install DECLINES and logs,
leaving the stock method in place -- a failure to instrument must never become
a failure to run. Verified True against the shipped triton here.

THE 8-BATCH COUNTER STAYS, with a reason. It is now redundant for module loads,
but `_post_cutover_build_batches` also stretches deadlines across the first
post-cutover forwards for reasons other than module loading (capture warmup,
first-touch allocations), and boot 23 measured it working (21/21 balanced). It
is cheap and it is the only thing with metal evidence behind it. Removing it in
the same commit that adds an untested broader mechanism would be trading a
proven narrow cover for an unproven wide one; it can go once this has a boot.

FUTURE CHECK: `devtools/check_1056_loader_chokepoint.py` drives the REAL
wrapped method with a stand-in kernel: a cold load opens exactly one window
naming the kernel, 50 warm launches open ZERO, a raising cold load propagates
unchanged AND leaves no window open. 7/7. It demonstrated its own can-fail on
the first run: the fixture lacked the early return, so install DECLINED and
three assertions failed -- the precondition guard firing correctly.

EVIDENCE TIER: DESK-PROVEN. Metal proof is boot 26.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 1, 2026
… load

boot_855_1072cut wedged 60 s after READY with every rank in the identical
frame (py-spy native, all three):

    MainThread  cuModuleLoadData <- loadBinary <- _init_handles
                <- _init_handles_in_window <- causal_conv1d_fn <- forward_extend
    watchdog    cuStreamSynchronize <- poll_status_word (barlink_bar1.py:4948)

0.0% CPU on every rank, GPU pinned at 100%, PCIe idle, log frozen for 20 s.
A cold Triton build is CPU-bound, so 0% CPU is the discriminator: the ranks
were not compiling, they were blocked in the driver. This thread's poll is a
copy plus `_abort_poll_stream.synchronize()`; it holds the CUDA context that
`cuModuleLoadData` needs. Closed cycle.

THIS IS THE MISSING AXIS OF AN EXISTING FIX, NOT A SECOND COPY OF IT. sgl-project#1056
(798e77b) wraps the Triton loader chokepoint and is present, is an ancestor,
is wired (scheduler.py:15292/15294) and RAN -- the wedged stack goes through
`_init_handles_in_window`, and the boot logged 233 window-OPEN lines. What it
does, verbatim from its docstring, is make "peers that reach a collective
deadline stretch that deadline instead of aborting the group". That is the
deadline axis. Its own docstring names the real cause one paragraph earlier
("the peers' spin kernels saturate the device"), but a stretched deadline does
not free a device. Consequence, and it is why the symptom no longer looks like
boot 22: sgl-project#1056 converted the CRASH class into a HANG class -- no
Bar1CollectiveAborted, just an indefinite stop.

The gap is structural: this watchdog is not a collective participant at all. It
runs on a timer in its own thread, so no deadline logic reaches it by
construction. barlink_liveness only ever consulted the window to SCALE ITS
TIMEOUT (:182-184, up to 40x); it never stopped polling.

THE BLINDNESS IS BOUNDED THREE WAYS, because a quiet liveness watchdog is the
thing this class exists to prevent:

  1. Only the DEVICE half stands down. `probe_once` keeps reading /proc, so a
     genuinely dead peer is still detected and still trips every abort window
     during the pause. A test pins that the host probe is not routed through
     the same guard.
  2. Resume needs no cleanup path. The suspension is re-decided every round,
     never latched, and `cold_build_window` closes in a `finally` on the
     normal AND the exception path. A poll that never comes back is silent,
     which is the failure direction that matters.
  3. The cap is the frist the PEERS already honour
     (`barlink_build_window.build_cap_s()`, default 900 s, this rig 60 s), not
     a second timer for the same deadline -- `in_cold_build_window()` is a bare
     depth counter with no clock, so a leaked depth would otherwise blind this
     thread for the life of the process.

Suspended rounds are counted and the span is logged on resume, so a quiet log
is a measured quiet rather than the next benign zero.

Also corrects the #1033c warmup line, which asserted "a minutes-long pause here
is a cold module load, not a wedge" UNCONDITIONALLY and on this boot invited
the reader to keep waiting through exactly this wedge. It now carries the
discriminator (%CPU) that separates the two.

Evidence: red-first measured against the tree without the fix -- 5 failed /
1 passed, the survivor being the host-probe guard, which is correct. With the
fix 6/6. Four mutants, each caught: never-suspends 3F, always-suspends 3F,
latches-and-never-resumes 1F (the silent killer, caught by the
exception-resume test), cap-bound-removed 1F. Full distributed suite A/B
against 141705c in a fresh worktree: 98 failing IDs on both sides, ZERO new,
+6 passed. Belegstufe: DESK-BEWIESEN, boot pending.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 26, 2026
…ller Rows-Formen, LMEM-Zensus am Triton-Loader -- rc9p D-TP0 starb am Local-Memory-Wachstum im ersten Launch der Form 16/1/2

Befund rc9p (dkrnfbar1rc9p09261011, Baum d1c7094, D-Log Z. 64368-64527):
10:34:24 'RuntimeError: Triton Error [CUDA]: out of memory' im Launch von
_sparse_attn_rows_fwd (sparse_attn.py:1000 <- _attend_rows :630 <-
_forward_extend_impl :1929). Z. 64404: 'QSA-ROWS-LAUNCH arch=sm120 kv=fp8
decode=exp2 cfg=16/1/2 first_total_q=3585' -- das X-Direkt-Extend weg2-22-25
(uncached=3585 auf 23744 Praefix, Z. 64384 sgl-project#969 EXTENT (...,23744,27329,23744,3585))
war der erste Request des Boots mit Praefix UND >512 neuen Zeilen. Alle
frueheren X-Admits mit Praefix <= 219 Zeilen; der 1423er war praefixfrei
(sgl-project#969 (...,0,1423,0,1423), Z. 13423 -> _sparse_gqa_prefill, STACK 32 B).

Wurzel: der L20-Tisch gibt >512 Zeilen (16, 1, 2). cuobjdump -res-usage im
Container-Triton-Cache (/spinning/docker-acceptance/nf/triton): die D-Variante
(fp8 exp2, USE_COUNTS=False) ist unter dem CUDA-13-Image (rc2.1d 8f1db7a,
PTX 9.0, SEVCQXIANJ...) REG 128 / STACK 2320 B je Thread; dieselbe Quelle
unter PTX 8.8 (63XNNJEYJA..., 25.09. 08:44) REG 255 / STACK 992 B. Der
Kontext hielt 1024 B (H15-Wake 'saved 1024', ganzer Boot) = 255 MiB; der
Launch musste auf 2320 B x 170 SM x 1536 = 578 MiB wachsen (gemessen
agent09252021, dieselbe Form bei 1153 Zeilen ueberlebt: 'WEG2-SLEEP-LMEM lmem
578->0 MiB ... NVML -580 MiB'), +323 MiB bzw. 578 MiB Neuanlage in
cuLaunchKernel, von keinem Posten gebucht; driver_free vor dem Extend 1706.8
MiB (Z. 64349), den Rest nahm das Extend selbst. Gruppe P fuhr die Form nie:
NF_ENV_P_FORM setzt SGLANG_FORCE_QSA_ROWS_CONFIG=inf=64/8/2 + FP8_DECODE=ptx,
Gruppe D hatte die Zeile nicht. Kein Modul-Unload: der sgl-project#1056-Wrapper feuert je
neuer Spezialisierung (rows: 4 Formen = 4 Loads, 12 Zeilen; l2norm_fwd_kernel
17x, T ist tl.constexpr).

Fix:
(a) sparse_attn._get_rows_config: sm120-Default = L20-Tisch mit NUR dem
    Eintrag >512 -> (64, 8, 2) (REG 152 / STACK 0 unter PTX 9.0, UZIGNZUEW4...
    = genau die D-Variante, im Container-Cache). Baender <=512 unveraendert,
    sm86 unveraendert, Env-Tisch gewinnt weiter. QSA-ROWS-LAUNCH traegt
    table=env|h101-sm120|l20|h20.
(b) qsa/rows_prewarm.py + Scheduler.warm_qsa_rows_forms (nach der Graph-
    Capture, vor der #603b-Barriere und dem ersten Sleep): jede Rows-Form x
    USE_COUNTS einmal gestartet, mit der Spezialisierung, die die Capture-
    Launches aufgezeichnet haben (Heads/HEAD_DIM/dtype/K/Pool-Strides, weak).
    Zeile 'H101 QSA-ROWS-PREWARM'. Form-A-Worker ueberspringen.
(c) utils/lmem_census.py am sgl-project#1056-Chokepoint: nach jedem Cold-Load wird
    LOCAL_SIZE (n_spills*4) gezaehlt; braucht der Kern mehr Stack als der
    Kontext haelt, wird er VOR dem ersten Launch per cuCtxSetLimit gebucht
    ('H101 LMEM-GROW ... action=grown'), bei Verweigerung empty_cache + ein
    Retry, danach 'H101 LMEM-GROW REFUSED' mit MiB. Der H15-Wake restauriert
    das Zensus-Maximum (booked=<B>(<kern>), auch ueber der H47-Kappe), die
    Sleep-Zeile traegt census=<B>(<kern>) (P-Planer-Regex unveraendert).

Tests: test_h101_rows_lmem (neu); H58/H65-Erwartung sm120 >512 auf (64,8,2)
nachgezogen; H15, 603b, prefill_config_h65 unveraendert.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 26, 2026
…ends statt aus aufgezeichneten Launches -- fnFL2h91bb2 waermte auf keinem Rang eine Form

Befund fnFL2h91bb2 (Baum e17bd54, D-Log boot_weg2_fnFL2h91bb2_e17bd548b5_0926_142251.D.log):
Z. 7739 TP0 14:29:54 'H101 QSA-ROWS-PREWARM skipped: no rows launch recorded
on this rank ... forms=[] stack None->None B census_max=0(-) ms=0'; P-Log
Z. 2545/2550/2569 PP2/PP1/PP0 dasselbe, TP1/TP2 Form-A-Worker. Die Tabelle
griff trotzdem (Z. 7646 cfg=32/8/2, Z. 11563 cfg=64/8/2 first_total_q=59,
table=h101-sm120): die Formen luden erst im Betrieb, mitten in echten Extends.

Wurzel: nicht "die Capture startet den Rows-Kern nicht" -- D-TP0 startete ihn
im Draft-Decode-Capture (14:29:51, Z. 7646 'QSA-ROWS-LAUNCH ... cfg=32/8/2
first_total_q=6', drei Sekunden VOR dem Prewarm). Die H101-Aufzeichnung hielt
den KV-Pool nur per weakref, und MHATokenToKVPool._get_key_buffer gibt bei
fp8-KV (store_dtype uint8 != dtype) 'k_buffer[slot].view(float8_e4m3fn)'
zurueck -- ein NEUES Tensor-Objekt je Aufruf, das nach dem Launch niemand
haelt: die Referenz war tot, rows_prewarm_signatures() filterte den Eintrag,
der Prewarm meldete 'skipped'. Auf P (PP0-2) laeuft vor dem Prewarm gar kein
Rows-Launch (keine Graph-Capture auf P). Der H101-Test pinnte die Aufzeichnung
mit einem vom Test gehaltenen Tensor und sah das nie.

Fix:
(a) sparse_attn: rows_prewarm_key/rows_prewarm_signature (ein Build-Schluessel
    fuer Aufzeichnung und Ableitung) und ein schwaches Provider-Register
    (register_rows_prewarm_provider, derived_rows_prewarm_signatures: je
    Build-Schluessel einmal, Fehler eines Providers benannt).
(b) QwenSparseAttnBackend registriert sich im __init__ und nennt mit
    rows_prewarm_signatures() seine Spezialisierung OHNE Launch: erster
    Full-Attention-Layer, den der Pool dieses Rangs haelt (RadixAttention,
    get_key_buffer wirft sonst), dessen q-Heads (unter DCP die Gruppensumme wie
    _attend_rows sie sammelt), head_dim, Modell-dtype, K = indexer_budget +
    compress_ratio - 1 (2051 auf NF), die Pool-Tensoren wie get_key_buffer sie
    ausgibt (fp8/16-bit waehlt die Decode-Variante); unter QSA-MTP-Index-Sharing
    zusaetzlich die geteilte Breite (K + num_steps + 1).
(c) rows_prewarm.run_boot_prewarm: Signaturen = abgeleitete zuerst, dann jede
    aufgezeichnete, deren Schluessel keine abgeleitete deckt; die Formen bleiben
    rows_launch_forms (Arch + Env-Tisch -> H101-Default -> H20/L20). Die Zeile
    traegt 'sigs=[24x256 bfloat16 K2051 kv=float8_e4m3fn (derived)]',
    Ableitungsfehler als 'derive ...' in errors. Skip nur noch, wenn weder ein
    Backend noch ein Launch etwas nennt. Ort unveraendert (nach der Capture, vor
    #603b und dem ersten Sleep), kein Schalter, keine Reserve.
LMEM: unveraendert ueber H101 (c) -- jede Prewarm-Ladung geht durch den
sgl-project#1056-Chokepoint (Zensus + Vorab-Wachstum), die erste WEG2-SLEEP-LMEM-Zeile
traegt census=, jeder H15-Wake restauriert census_max (booked=); damit wird
eine spillende Form (sm86 L20 >512: 16/1/2) beim Boot gebucht statt in einem
Serving-Launch.

Tests test_h101b_rows_prewarm_derived (9, CUDA gemockt wie H101): D-TP0-Form
(fp8-View-Pool, sm120-Tisch, 8 Launches ohne Aufzeichnung), P-Stufe sm86
inf=64/8/2 ptx, Ziel+Draft ein Build, MTP-Sharing zweite Breite, DCP-Heads,
benannter Skip, werfender Provider, Zensus -> Wake bucht 2320. Basis e17bd54:
8 rot, 1 gruen (der Metall-Test: die Aufzeichnung ist leer -- belegt die Wurzel);
mit Fix 9 gruen. Betroffene Suiten (11 Dateien): Basis 10 rot / 101 gruen, Fix
2 rot / 109 gruen; die 2 Roten sind Altlasten identisch auf der Basis
(test_qsa_sparse_rows_dcp_wp3b: Stubs ohne row_counts). test_h101_rows_lmem
unveraendert gruen.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 26, 2026
… und D (27B-Kern 6b24aa6 uebernommen) + Boot-Prewarm -- kein Triton-Cold-Load je Extend-Laenge

Befund rc9p (dkrnfbar1rc9p09261011, Baum d1c7094): l2norm_fwd_kernel
(fla/l2norm.py:55) fuehrt T (Tokens x Koepfe) und NB = cdiv(T, 2048) als
tl.constexpr, also ist jede neue Extend-Laenge ein neuer Triton-Kern, auf dem
Scheduler-Thread im Launch kompiliert bzw. von Platte geladen. sgl-project#1056-Fenster
nach READY: D-Log 15 Loads, alle TP0, alle D-Extend, 16,7 s summiert, davon
10:34:11 12,7 s (X-Direkt-Extend weg2-22-25, 3585 neue Zeilen; Z. 64388-64393)
und 5 weitere 0,5-1,2 s (Compile), 9 Platten-Treffer < 0,1 s; P-Log 78 Loads
(26 je Stufe, je < 0,1 s). Vergleich: x177 D 7 Loads / 1,1 s, P 27;
fnFL2h91v1 D 12, P 24. Jeder andere FLA/GDN-Kern laedt beschraenkt oft (T ist
dort schon Laufzeitargument mit do_not_specialize, chunk_delta_h bucketet NT);
l2norm_fwd_kernel ist der einzige mit T als constexpr (AST-Scan fla/ + mamba/).
Upstream-FLA fuehrt T zur Laufzeit (@triton.jit(do_not_specialize=["T"])),
Upstream-sglang (main) noch als constexpr.

Fix:
(a) fla/l2norm.py = 27B-Strang 6b24aa6 wortgleich (Blob 2d33509):
    l2norm_fwd_kernel_rt, derselbe Kernkoerper, T Laufzeitargument
    (do_not_specialize), kein NB, BT=16/num_warps=8/num_stages=3, Gitter
    cdiv(T, 16); gewaehlt bei SGLANG_FLA_L2NORM_RUNTIME_T=1 (D <= 512), sonst
    der Stock-Kern. Eine Spezialisierung je (dtype, D, BD).
(b) weg2/launcher.build_env setzt SGLANG_FLA_L2NORM_RUNTIME_T=1 per setdefault
    fuer BEIDE Gruppen (im 27B-Strang nur P ueber --p-host-overlap); Operator-
    Wert und --env-p/--env-d gewinnen.
(c) fla/l2norm_prewarm.py + Scheduler.warm_fla_l2norm (hinter H101s
    warm_qsa_rows_forms, vor der #603b-Barriere und dem ersten Sleep): ein
    Launch [16, linear_key_head_dim] im Modell-dtype -- exakt der Serving-
    Schluessel --, Zeile 'H103 FLA-L2NORM-PREWARM'; uebersprungen (benannt)
    bei Schalter aus, Form-A-Worker, Modell ohne GDN; wirft nie. 4 KiB Scratch,
    kein neuer VRAM ausser dem Cubin.

Tests: test_h103_fla_l2norm_runtime_t (neu): Tritons eigener Binder +
compute_cache_key (sm_120 und sm_86, nur der Launch gemockt) sieht ueber 307
Extend-Laengen EINE Spezialisierung, der Stock-Kern 307; der Prewarm-Launch hat
den Serving-Schluessel; build_env P/D; Operator gewinnt; Scheduler-Reihenfolge;
Triton-Interpreter: Laufzeit-Variante == Stock-Kern BITGLEICH (fp32 und bf16,
16 Faelle). 12 gruen mit Fix, 10 rot auf d1c7094 (Kern: 307
Spezialisierungen statt 1). Auf H101 gestapelt (Scheduler-Naht: warm_fla_l2norm
direkt hinter warm_qsa_rows_forms) mit test_h101_rows_lmem: 34 gruen.
Betroffene Suiten (24 Dateien, build_env/Scheduler/GDN): 806 gruen, 9 rot, dieselben 9
auf d1c7094 rot (Altlasten, 0 neu). Metall-Bitgleichheit (sm_120/sm_86) steht
aus (h103/work/metal_l2norm_h103.py).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants