Official Inference Code of EAGLE-4
fix(sglang): capture first-use graphs without flushing the allocator
Seyfal Sultanovd4cbd5d7421b
diff --git a/eagle_harness/kernels/row_attention.py b/eagle_harness/kernels/row_attention.pyindex 5594dc3..2385b69 100644--- a/eagle_harness/kernels/row_attention.py+++ b/eagle_harness/kernels/row_attention.py@@ -7,7 +7,8 @@ A request's rows see one range of its committed keys, read through its page tablalso see their own tree ancestors:- draft step ``step`` (``rows`` frontier rows per request, all at position ``seq_len + step - 1``): the committed keys- inside the draft's sliding window, the same for every row, plus the row's ``step`` ancestors (itself last);+ of the window ending at the round's last committed position, ``[seq_len - window, seq_len - 1]`` (frozen for the+ round, as the draft was trained), the same for every row, plus the row's ``step`` ancestors (itself last);- draft extend (``step == 0``; row ``j`` at ``seq_len + j``): the keys ``[pos - window + 1, pos]`` of its own position.One program per (request, head, key split) loads each key and value of the request's range once for all its rows@@ -135,8 +136,8 @@ def _rows_attention_kernel(if EXTEND:first = tl.min(tl.where(row_ok, lo, 2147483647), 0)last = tl.max(tl.where(row_ok, hi, -1), 0)- else: # every row sees the committed keys of the window at seq_len + step - 1- first = tl.minimum(window_start(seq_len + step - 1, window), seq_len)+ else: # every row sees the committed keys of the window frozen at the last committed position+ first = window_start(seq_len - 1, window)last = seq_len - 1if table_rows is None:row_pages = table + b * stride_tablediff --git a/eagle_harness/models/eagle4_config.py b/eagle_harness/models/eagle4_config.pyindex fcfa632..3ce4832 100644--- a/eagle_harness/models/eagle4_config.py+++ b/eagle_harness/models/eagle4_config.py@@ -7,7 +7,8 @@ Checks supported keys and structural constraints in a transformers config.Pure Python: no engine, no GPU.Sliding-window semantics, as trained: at draft depth d a query attends to at-most W context keys ending at it plus the d draft tokens of its own chain.+most W context keys, ending at the round's last committed position, plus the+d draft tokens of its own chain.Activation: an explicit ``layer_types`` wins, then ``use_sliding_window``, anda positive ``sliding_window`` alone enables the window. Single-layer drafts only."""diff --git a/eagle_harness/sglang/graph_pool.py b/eagle_harness/sglang/graph_pool.pyindex 36a2edd..62de016 100644--- a/eagle_harness/sglang/graph_pool.py+++ b/eagle_harness/sglang/graph_pool.py@@ -1,10 +1,12 @@# Copyright 2026 Eagle AI Corp.# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available-"""The CUDA graph memory pool the harness's graphs share with sglang's."""+"""The CUDA graph memory pool the harness's graphs share with sglang's, and captures between served rounds."""from __future__ import annotations+from typing import Callable, Dict, Tuple, TypeVar+import torchfrom sglang.srt.model_executor.runner_utils.pool import get_global_graph_memory_pool, set_global_graph_memory_pool@@ -17,3 +19,42 @@ def graph_memory_pool():pool = torch.cuda.graph_pool_handle()set_global_graph_memory_pool(pool)return pool+++T = TypeVar("T")+_capture_streams: Dict[int, torch.cuda.Stream] = {}+_anchors: Dict[object, torch.cuda.CUDAGraph] = {} # pool handle -> a graph that keeps the pool's use count above 0+++def capture(body: Callable[[], T]) -> Tuple[torch.cuda.CUDAGraph, T]:+ """Capture ``body()`` into a CUDA graph in the shared pool, for a graph first needed while serving.++ ``torch.cuda.graph`` synchronizes the device and empties the allocator's device and pinned-host caches before it+ captures. Between served rounds that drains the GPU queue and frees every cached block, which the next rounds+ allocate again: 20-30 ms per first-use capture on a TP4 batch-1 round. A capture only records work, so this+ captures on a side stream ordered after the current one, with neither.++ The cache flush also deletes a pool whose graphs were all freed; capturing into such a pool again without it+ fails an allocator assert. So the first capture into a pool goes through ``torch.cuda.graph`` once and keeps a+ small anchor graph in it, and the pool stays alive for every later capture.+ """+ pool = graph_memory_pool()+ if pool not in _anchors:+ anchor = torch.cuda.CUDAGraph()+ with torch.cuda.graph(anchor, pool=pool, capture_error_mode="thread_local"):+ torch.zeros(1, device="cuda")+ _anchors[pool] = anchor+ device = torch.cuda.current_device()+ stream = _capture_streams.get(device)+ if stream is None:+ stream = _capture_streams[device] = torch.cuda.Stream()+ stream.wait_stream(torch.cuda.current_stream())+ graph = torch.cuda.CUDAGraph()+ with torch.cuda.stream(stream):+ graph.capture_begin(pool=pool, capture_error_mode="thread_local")+ try:+ outputs = body()+ finally:+ graph.capture_end()+ torch.cuda.current_stream().wait_stream(stream)+ return graph, outputsdiff --git a/eagle_harness/sglang/row_attention.py b/eagle_harness/sglang/row_attention.pyindex c7ef416..1427d53 100644--- a/eagle_harness/sglang/row_attention.py+++ b/eagle_harness/sglang/row_attention.py@@ -6,8 +6,9 @@The rows of a request share most of their keys; :mod:`eagle_harness.kernels.row_attention` attends them, readingthe keys through sglang's ``req_to_token`` (one token per page, rows picked by ``req_pool_indices``):-- draft step ``i`` (``K`` frontier rows per request at position ``seq_len[b] + i - 1``): the committed draft KV inside- the draft's sliding window plus the row's ``i`` tree ancestors, whose KV slots :attr:`DraftTree.ancestors` keeps+- draft step ``i`` (``K`` frontier rows per request at position ``seq_len[b] + i - 1``): the committed draft KV of the+ window frozen at the round's last committed position, ``[seq_len[b] - window, seq_len[b] - 1]``, plus the row's+ ``i`` tree ancestors, whose KV slots :attr:`DraftTree.ancestors` keeps(:meth:`DraftRowAttention.build_tree_rows` also allocates the step's slots and records them as the new ancestors);- draft extend (``W`` causal rows per request at ``seq_len[b] + j``): the positions ``[pos - window + 1, pos]``.diff --git a/eagle_harness/sglang/verify_step.py b/eagle_harness/sglang/verify_step.pyindex c6b7d5c..2ea0b06 100644--- a/eagle_harness/sglang/verify_step.py+++ b/eagle_harness/sglang/verify_step.py@@ -30,7 +30,7 @@ import torchfrom sglang.srt.speculative.eagle_worker_common import VerifyAcceptInput, VerifyAcceptResult, VerifyAcceptStepfrom eagle_harness.kernels.accept_tail import Accepted, accept_tail, compact_rows-from eagle_harness.sglang.graph_pool import graph_memory_pool+from eagle_harness.sglang.graph_pool import captureif TYPE_CHECKING:from sglang.srt.managers.schedule_batch import ScheduleBatch@@ -82,10 +82,7 @@ class AcceptTailGraphs:if len(self._seen) < 4 * MAX_TAIL_GRAPHS:self._seen.add(key)return body()- graph = torch.cuda.CUDAGraph()- with torch.cuda.graph(graph, pool=graph_memory_pool(), capture_error_mode="thread_local"):- outputs = body()- entry = self._graphs[key] = (graph, outputs)+ entry = self._graphs[key] = capture(body)if len(self._graphs) == MAX_TAIL_GRAPHS:logger.warning("eagle-harness: %d accept-tail graphs; new verify layouts run eagerly", MAX_TAIL_GRAPHS)graph, outputs = entrydiff --git a/eagle_harness/sglang/verify_tail.py b/eagle_harness/sglang/verify_tail.pyindex 8606f52..c3095f2 100644--- a/eagle_harness/sglang/verify_tail.py+++ b/eagle_harness/sglang/verify_tail.py@@ -25,7 +25,7 @@ import torchfrom sglang.srt.speculative.eagle_info import EagleVerifyInputfrom eagle_harness.core.draft_tree import DraftTree, VerifySelection-from eagle_harness.sglang.graph_pool import graph_memory_pool+from eagle_harness.sglang.graph_pool import capture# (batch size, tree selection, num_steps, num_draft_tokens) -> sglang's verify input.BuildInput = Callable[[int, VerifySelection, int, int], EagleVerifyInput]@@ -41,10 +41,7 @@ class Ranking(NamedTuple):def _capture(body: Callable[[], object]):"""Run ``body`` once eagerly (Triton compiles), then capture it; returns ``(graph, outputs)``."""body()- graph = torch.cuda.CUDAGraph()- with torch.cuda.graph(graph, pool=graph_memory_pool(), capture_error_mode="thread_local"):- outputs = body()- return graph, outputs+ return capture(body)class VerifyTail:diff --git a/tests/test_eagle3_attention.py b/tests/test_eagle3_attention.pyindex e91a002..493d40d 100644--- a/tests/test_eagle3_attention.py+++ b/tests/test_eagle3_attention.py@@ -47,7 +47,7 @@ def test_native_grouped_query_draft_rows(step, window):table_rows=req,)for row in range(4):- position = 16 + (row if step == 0 else step - 1)+ position = 16 + row if step == 0 else 15 # a draft step's window ends at the last committed positionstart = max(0, position - window + 1) if window else 0keys = list(range(start, position + 1 if step == 0 else 16))if step:diff --git a/tests/test_graph_capture_gpu.py b/tests/test_graph_capture_gpu.pynew file mode 100644index 0000000..7fbd8a3--- /dev/null+++ b/tests/test_graph_capture_gpu.py@@ -0,0 +1,52 @@+# Copyright 2026 Eagle AI Corp.+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available++"""A capture between served rounds keeps the allocator's caches and the GPU queue (skipped without CUDA).++Run in a GPU job: ``pytest -q tests/test_graph_capture_gpu.py``.+"""++from unittest import mock++import pytest+import torch++pytest.importorskip("sglang")++from eagle_harness.sglang import graph_pool # noqa: E402++pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device")+++def test_capture_replays_the_body_without_flushing_or_syncing():+ x = torch.arange(1024, dtype=torch.float32, device="cuda")+ out = torch.empty_like(x)++ def body():+ torch.mul(x, 2.0, out=out)+ return out + 1.0++ body() # eager first round, as the callers do+ graph_pool.capture(body) # the pool's first capture may flush once (it anchors the pool)+ reserved = torch.cuda.memory_reserved()+ with (+ mock.patch.object(torch.cuda, "empty_cache", side_effect=AssertionError("empty_cache")),+ mock.patch.object(torch.cuda, "synchronize", side_effect=AssertionError("synchronize")),+ ):+ graph, result = graph_pool.capture(body)+ assert torch.cuda.memory_reserved() >= reserved # nothing the rounds cached was released++ x.fill_(3.0) # written on the current stream: the replay must see it+ graph.replay()+ torch.cuda.current_stream().synchronize()+ assert torch.equal(result, torch.full_like(x, 7.0))+ assert torch.equal(out, torch.full_like(x, 6.0))+++def test_capture_into_a_pool_whose_graphs_were_all_freed():+ x = torch.ones(8, device="cuda")+ for _ in range(3): # each round frees every graph it captured, as a finished test or request does+ graph, out = graph_pool.capture(lambda: x * 2.0)+ graph.replay()+ assert torch.equal(out, torch.full_like(x, 2.0))+ del graph, outdiff --git a/tests/test_row_attention_gpu.py b/tests/test_row_attention_gpu.pyindex 2ff8b23..37e0136 100644--- a/tests/test_row_attention_gpu.py+++ b/tests/test_row_attention_gpu.py@@ -107,7 +107,7 @@ def test_tree_rows_attend_window_and_ancestors(bs, step, window, low, high):for b in range(bs):length = int(seq_lens[b])- start = max(length + step - 1 - window + 1, 0) if window > 0 else 0+ start = max(length - window, 0) if window > 0 else 0 # the window frozen at the last committed positionfor lane in range(K):keys = torch.cat([req_to_token[req[b], start:length], ancestors[b, lane, :step]]).long()want = _reference(q[b * K + lane], k_buffer, v_buffer, keys, HEAD_DIM**-0.5)@@ -182,19 +182,20 @@ def test_nemotron_window_boundary(heads, length, step):partial,lse,table,- req,seq,ancestors,rows_per_request=rows,step=step,window=window,scale=dim**-0.5,+ launch=EXTEND_LAUNCH if step == 0 else STEP_LAUNCH,+ table_rows=req,)return out.clone()got = run()for row in range(rows):- pos = length + (step - 1 if step else row)+ pos = length - 1 if step else length + row # a draft step's window ends at the last committed positionstart = max(pos - window + 1, 0)if step:assert ancestors is not None@@ -205,7 +206,7 @@ def test_nemotron_window_boundary(heads, length, step):torch.testing.assert_close(got[row].float(), want, atol=2e-2, rtol=2e-2)# Every row excludes this prefix. Poisoning it must not affect the result.- dropped = max(length + (step - 1 if step else 0) - window + 1, 0)+ dropped = max(length - window + (0 if step else 1), 0)k[table[0, :dropped].long()] = 100v[table[0, :dropped].long()] = -100assert torch.equal(got, run())diff --git a/tests/test_tree_step_attention.py b/tests/test_tree_step_attention.pyindex 7eea98b..cf5c803 100644--- a/tests/test_tree_step_attention.py+++ b/tests/test_tree_step_attention.py@@ -50,9 +50,9 @@ def test_tree_step_attention_matches_dense_torch(bs, step, committed, window, grgot = tree_step_attention(q, kv, table, table_block, committed_t, ancestors, d**-0.5, step=step, window=window)flat = kv.reshape(-1, kv_heads, 2 * d).repeat_interleave(group_size, dim=1).float()for b in range(bs):- # each row sees the committed keys inside the window of its position c + step - 1, then its own ancestors+ # each row sees the window frozen at the last committed position c - 1, then its own ancestorsc = committed[b]- start = min(max(0, c + step - window), c) if window else 0+ start = max(0, c - window) if window else 0prefix = [int(table[b, p // table_block]) * table_block + p % table_block for p in range(start, c)]for lane in range(top_k):r = b * top_k + lane@@ -119,7 +119,7 @@ def test_shared_rows_gqa_matches_torch_and_repeated_mha(group_size, packed, stepfor b in range(bs):length = int(lengths[b])for row in range(rows):- pos = length + (step - 1 if step else row)+ pos = length - 1 if step else length + row # a draft step's window ends at the last committed positionstart = max(0, pos - window + 1) if window else 0end = length if step else pos + 1selected = table[table_rows[b], min(start, end) : end]