Official Inference Code of EAGLE-4
refactor(vllm): move the test-only draft attention and depth-stop references out of the package
Seyfal Sultanov427ce56b02f4
diff --git a/eagle_harness/vllm/depth_stop.py b/eagle_harness/vllm/depth_stop.pyindex 9c0c2a2..dfd3b18 100644--- a/eagle_harness/vllm/depth_stop.py+++ b/eagle_harness/vllm/depth_stop.py@@ -130,30 +130,6 @@ def derived_cost_tables(return tables-def keep_growing_reference(- scores: torch.Tensor,- decay: torch.Tensor,- front: torch.Tensor,- count: int,- next_decay: float,- min_gain: float,- parent_layer: tuple[int, int],- step_share: float = 0.0,-) -> torch.Tensor:- """The rule in torch: ``scores`` ``[bs, nodes]`` (0 where no node was grown), ``decay`` ``[nodes]``, ``front``- ``[bs, K]`` the frontier's scores (the newest layer's best), ``parent_layer`` the node range of the layer above the- newest, ``step_share`` :meth:`RoundCosts.step_share`; a scalar bool."""- ranked = torch.sort(scores * decay, dim=-1, descending=True).values- threshold = ranked[:, count - 1 : count]- reach = front * torch.tensor(next_decay, dtype=torch.float32, device=front.device)- parent_best = scores[:, parent_layer[0] : parent_layer[1]].max(-1, keepdim=True).values- ratio = front.max(-1, keepdim=True).values / parent_best.clamp(min=1e-30)- gain = (reach * ratio - threshold).clamp(min=0).sum(-1)- expected = 1.0 + ranked[:, :count].sum(-1)- keep = (reach.max(-1).values >= threshold[:, 0]) & (gain >= min_gain + step_share * expected)- return keep.any()--@triton.jitdef _keep_growing_kernel(scores,diff --git a/eagle_harness/vllm/draft_attention.py b/eagle_harness/vllm/draft_attention.pyindex 7cbcd38..0b564a2 100644--- a/eagle_harness/vllm/draft_attention.py+++ b/eagle_harness/vllm/draft_attention.py@@ -10,221 +10,14 @@ length), writing its draft KV to a slot past ``c`` and attending to- the row's own ``s`` tree ancestors, itself last, whose slots :attr:`DraftTree.ancestors` keeps.:func:`tree_step_attention` reads those keys through the block table and loads each committed key once for all the-rows of a request (:mod:`eagle_harness.kernels.row_attention`, the kernel sglang's draft uses). The per-row pair-:func:`build_tree_rows` + :func:`row_attention` (each row a one-token decode over an explicit list of KV slots) is-its reference.+rows of a request (:mod:`eagle_harness.kernels.row_attention`, the kernel sglang's draft uses)."""from __future__ import annotationsimport torch-import triton-import triton.language as tl-from eagle_harness.kernels.row_attention import RowsLaunch, program_splits, rows_attention, rows_padded, window_start--KEYS_PER_SPLIT = 512-MAX_SPLITS = 16-BLOCK_KEYS = 64-_BUILD_BLOCK = 1024---def _tree_rows_kernel(- block_table_ptr, # [num_reqs, max_blocks] int32 of the draft KV group, by batch row- stride_table,- block_size,- committed_ptr, # [num_reqs] committed draft length c- ancestors_ptr, # [num_reqs, K, max_depth] int32: draft KV slot of each frontier row's ancestors- keys_ptr, # [rows, max_keys] int32 out- stride_keys,- num_keys_ptr, # [rows] int32 out- step,- window,- max_depth: tl.constexpr,- top_k: tl.constexpr,- BLOCK: tl.constexpr,-):- row = tl.program_id(0)- chunk = tl.program_id(1)- b = row // top_k- committed = tl.load(committed_ptr + b).to(tl.int32)- start = window_start(committed + step - 1, window)- start = tl.minimum(start, committed)- prefix = committed - start- total = prefix + step- offs = chunk * BLOCK + tl.arange(0, BLOCK)- position = start + offs- block = tl.load(block_table_ptr + b * stride_table + position // block_size, mask=offs < prefix, other=0)- slot = block.to(tl.int32) * block_size + position % block_size- ancestor = tl.load(- ancestors_ptr + row * max_depth + (offs - prefix), mask=(offs >= prefix) & (offs < total), other=0- )- tl.store(keys_ptr + row * stride_keys + offs, tl.where(offs < prefix, slot, ancestor), mask=offs < total)- if chunk == 0:- tl.store(num_keys_ptr + row, total)---def build_tree_rows(- block_table: torch.Tensor,- block_size: int,- committed: torch.Tensor,- ancestors: torch.Tensor,- keys: torch.Tensor,- num_keys: torch.Tensor,- *,- step: int,- window: int,-) -> None:- """Key lists of draft step ``step`` for the ``bs * K`` frontier rows (``ancestors``: ``[bs, K, depth]``)."""- bs, top_k, max_depth = ancestors.shape- _tree_rows_kernel[(bs * top_k, triton.cdiv(keys.shape[1], _BUILD_BLOCK))](- block_table,- block_table.stride(0),- block_size,- committed,- ancestors,- keys,- keys.stride(0),- num_keys,- step,- window,- max_depth=max_depth,- top_k=top_k,- BLOCK=_BUILD_BLOCK,- )---def _row_attention_split_kernel(- q_ptr, # [rows, H, D]- kv_ptr, # KV cache base- keys_ptr, # [rows, max_keys] int32 KV slots- stride_keys,- num_keys_ptr, # [rows]- partial_ptr, # [rows, H, SPLITS, D] fp32- partial_lse_ptr, # [rows, H, SPLITS] fp32- stride_qr,- stride_qh,- stride_block,- stride_head,- stride_slot,- block_size,- scale,- D: tl.constexpr,- H: tl.constexpr,- QUERY_GROUP_SIZE: tl.constexpr,- SPLITS: tl.constexpr,- PER_SPLIT: tl.constexpr,- BLOCK: tl.constexpr,-):- row, head, split = tl.program_id(0), tl.program_id(1), tl.program_id(2)- num_keys = tl.load(num_keys_ptr + row)- lo = split * PER_SPLIT- hi = tl.minimum(lo + PER_SPLIT, num_keys)- dims = tl.arange(0, D)- q = tl.load(q_ptr + row * stride_qr + head * stride_qh + dims).to(tl.float32)- peak = tl.full([], float("-inf"), dtype=tl.float32)- total = tl.zeros([], dtype=tl.float32)- acc = tl.zeros([D], dtype=tl.float32)- for first in range(lo, hi, BLOCK):- offs = first + tl.arange(0, BLOCK)- valid = offs < hi- slot = tl.load(keys_ptr + row * stride_keys + offs, mask=valid, other=0).to(tl.int64)- at = (- (slot // block_size) * stride_block- + (head // QUERY_GROUP_SIZE) * stride_head- + (slot % block_size) * stride_slot- )- k = tl.load(kv_ptr + at[:, None] + dims[None, :], mask=valid[:, None], other=0.0).to(tl.float32)- scores = tl.sum(k * q[None, :], 1) * scale- scores = tl.where(valid, scores, float("-inf"))- new_peak = tl.maximum(peak, tl.max(scores, 0))- weights = tl.exp(scores - new_peak)- rescale = tl.exp(peak - new_peak)- v = tl.load(kv_ptr + at[:, None] + D + dims[None, :], mask=valid[:, None], other=0.0).to(tl.float32)- acc = acc * rescale + tl.sum(weights[:, None] * v, 0)- total = total * rescale + tl.sum(weights, 0)- peak = new_peak- out = (row * H + head) * SPLITS + split- tl.store(partial_ptr + out * D + dims, acc / total)- tl.store(partial_lse_ptr + out, peak + tl.log(total))---def _row_attention_merge_kernel(- partial_ptr,- partial_lse_ptr,- num_keys_ptr,- out_ptr, # [rows, H, D]- H: tl.constexpr,- D: tl.constexpr,- SPLITS: tl.constexpr,- PER_SPLIT: tl.constexpr,-):- row, head = tl.program_id(0), tl.program_id(1)- num_splits = tl.cdiv(tl.load(num_keys_ptr + row), PER_SPLIT)- splits = tl.arange(0, SPLITS)- base = (row * H + head) * SPLITS- lse = tl.load(partial_lse_ptr + base + splits, mask=splits < num_splits, other=float("-inf"))- weights = tl.exp(lse - tl.max(lse, 0))- parts = tl.load(- partial_ptr + (base + splits)[:, None] * D + tl.arange(0, D)[None, :],- mask=(splits < num_splits)[:, None],- other=0.0,- )- out = tl.sum(parts * (weights / tl.sum(weights, 0))[:, None], 0)- tl.store(out_ptr + (row * H + head) * D + tl.arange(0, D), out.to(out_ptr.dtype.element_ty))---def row_attention(- q: torch.Tensor,- key_cache: torch.Tensor,- keys: torch.Tensor,- num_keys: torch.Tensor,- scale: float,-) -> torch.Tensor:- """One-token attention of ``rows`` queries ``[rows, H, D]`` over the KV slots in ``keys``.-- ``key_cache``: the layer's KV cache viewed ``[blocks, slots in a block, heads, 2 * D]`` (K then V of a token).- """- rows, num_heads, head_dim = q.shape- kv_heads = key_cache.shape[2]- if kv_heads <= 0 or num_heads % kv_heads:- raise ValueError(f"query heads ({num_heads}) must be divisible by KV heads ({kv_heads})")- block_size = key_cache.shape[1]- max_splits = triton.cdiv(keys.shape[1], KEYS_PER_SPLIT)- splits = min(triton.next_power_of_2(max_splits), MAX_SPLITS)- per_split = triton.cdiv(keys.shape[1], splits)- partial = torch.empty((rows, num_heads, splits, head_dim), dtype=torch.float32, device=q.device)- partial_lse = torch.empty((rows, num_heads, splits), dtype=torch.float32, device=q.device)- out = torch.empty_like(q)- _row_attention_split_kernel[(rows, num_heads, splits)](- q,- key_cache,- keys,- keys.stride(0),- num_keys,- partial,- partial_lse,- q.stride(0),- q.stride(1),- key_cache.stride(0),- key_cache.stride(2),- key_cache.stride(1),- block_size,- scale,- D=head_dim,- H=num_heads,- QUERY_GROUP_SIZE=num_heads // kv_heads,- SPLITS=splits,- PER_SPLIT=per_split,- BLOCK=BLOCK_KEYS,- )- _row_attention_merge_kernel[(rows, num_heads)](- partial, partial_lse, num_keys, out, H=num_heads, D=head_dim, SPLITS=splits, PER_SPLIT=per_split- )- return out+from eagle_harness.kernels.row_attention import RowsLaunch, program_splits, rows_attention, rows_padded# Keys per iteration of :func:`tree_step_attention` (a [rows, 128] x [128, D] tile per step).@@ -247,8 +40,7 @@ def tree_step_attention(``key_cache``: the layer's KV cache viewed ``[blocks, slots, heads, 2 * D]``; ``block_table[b]`` maps request``b``'s positions to blocks of ``table_block`` tokens; ``ancestors`` ``[bs, K, depth]`` holds flat token slots.- The window is cut into about one program per SM in all. Same keys as :func:`build_tree_rows` +- :func:`row_attention`.+ The window is cut into about one program per SM in all."""_, heads, head_dim = q.shapebs, top_k, _ = ancestors.shapediff --git a/tests/test_depth_stop.py b/tests/test_depth_stop.pyindex 0bcdce5..3f21dfd 100644--- a/tests/test_depth_stop.py+++ b/tests/test_depth_stop.py@@ -44,11 +44,34 @@ def _probs(gen: torch.Generator, rows: int, sharpness: torch.Tensor) -> torch.Tereturn torch.topk(logits.softmax(-1), K, dim=-1).values+def keep_growing_reference(+ scores: torch.Tensor,+ decay: torch.Tensor,+ front: torch.Tensor,+ count: int,+ next_decay: float,+ min_gain: float,+ parent_layer: tuple[int, int],+ step_share: float = 0.0,+) -> torch.Tensor:+ """The rule of :func:`~eagle_harness.vllm.depth_stop.keep_growing` in torch: ``scores`` ``[bs, nodes]`` (0 where no+ node was grown), ``decay`` ``[nodes]``, ``front`` ``[bs, K]`` the frontier's scores (the newest layer's best),+ ``parent_layer`` the node range of the layer above the newest, ``step_share`` :meth:`RoundCosts.step_share`; a+ scalar bool."""+ ranked = torch.sort(scores * decay, dim=-1, descending=True).values+ threshold = ranked[:, count - 1 : count]+ reach = front * torch.tensor(next_decay, dtype=torch.float32, device=front.device)+ parent_best = scores[:, parent_layer[0] : parent_layer[1]].max(-1, keepdim=True).values+ ratio = front.max(-1, keepdim=True).values / parent_best.clamp(min=1e-30)+ gain = (reach * ratio - threshold).clamp(min=0).sum(-1)+ expected = 1.0 + ranked[:, :count].sum(-1)+ keep = (reach.max(-1).values >= threshold[:, 0]) & (gain >= min_gain + step_share * expected)+ return keep.any()++def _grow(bs: int, count: int, seed: int, min_gain: float | None):"""Grow a tree on CPU with the reference step; with ``min_gain`` stop as the rule says. Returns``(verify node set per request, steps run)``."""- from eagle_harness.vllm.depth_stop import keep_growing_reference-gen = torch.Generator().manual_seed(seed)sharp = torch.rand(bs, generator=gen) * 6 # some requests confident, some nottree = _tree(bs)@@ -94,8 +117,6 @@ def test_a_positive_gain_stops_no_later():def test_reference_rule_on_a_hand_made_tree():- from eagle_harness.vllm.depth_stop import keep_growing_reference-def keep(front, gain, parent=(1, 2), scores=torch.tensor([[0.9, 0.5, 0.2, 0.1, 0.0]])):return bool(keep_growing_reference(scores, torch.ones(5), torch.tensor(front), 3, 1.0, gain, parent))@@ -113,8 +134,6 @@ def test_reference_rule_on_a_hand_made_tree():def test_reference_prices_a_step_by_the_expected_accept():- from eagle_harness.vllm.depth_stop import keep_growing_reference-scores = torch.tensor([[0.9, 0.5, 0.2, 0.1, 0.0]])def keep(share, gain=0.0):@@ -157,7 +176,7 @@ def test_kernel_prices_a_step_by_the_expected_accept(share, keeps):],)def test_kernel_matches_the_reference(bs, count, gain, share):- from eagle_harness.vllm.depth_stop import keep_growing, keep_growing_reference+ from eagle_harness.vllm.depth_stop import keep_growingdevice = "cuda" if torch.cuda.is_available() else "cpu"shape = TreeShape(top_k=K, max_depth=DEPTH)diff --git a/tests/test_gpu_kernels.py b/tests/test_gpu_kernels.pyindex c9a5b78..5b67be1 100644--- a/tests/test_gpu_kernels.py+++ b/tests/test_gpu_kernels.py@@ -10,7 +10,6 @@ pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a G# a CPU-only vLLM build lacks the FlashAttention entry points the tree attention importspytest.importorskip("eagle_harness.vllm.tree_attention", reason="needs vLLM's GPU build", exc_type=ImportError)-from eagle_harness.vllm.draft_attention import build_tree_rows, row_attention # noqa: E402from eagle_harness.vllm.round_commit import KvCompactor # noqa: E402from eagle_harness.vllm.verify_layout import TreeStore, VerifyStage # noqa: E402@@ -65,38 +64,6 @@ def test_stage_depths_masks_and_window_ancestors(parents):assert int(stage.context_lens[b]) == 100 # the first query token's chain position-def test_row_attention_matches_dense():- torch.manual_seed(0)- blocks, block_size, h, d, rows, n = 8, 16, 4, 128, 5, 100- stored = torch.randn(blocks, h, block_size, 2 * d, device=DEV, dtype=torch.bfloat16)- cache = stored.transpose(1, 2) # the backend's view: (blocks, slots, heads, 2 * head_dim)- q = torch.randn(rows, h, d, device=DEV, dtype=torch.bfloat16)- keys = torch.randint(0, blocks * block_size, (rows, n), device=DEV, dtype=torch.int32)- num_keys = torch.tensor([n, 1, 37, 64, 99], dtype=torch.int32, device=DEV)- out = row_attention(q, cache, keys, num_keys, d**-0.5)- flat = cache.reshape(-1, h, 2 * d)- for r in range(rows):- kv = flat[keys[r, : num_keys[r]].long()].float()- scores = torch.einsum("hd,khd->hk", q[r].float(), kv[..., :d]) * d**-0.5- want = torch.einsum("hk,khd->hd", scores.softmax(-1), kv[..., d:])- torch.testing.assert_close(out[r].float(), want, atol=2e-2, rtol=2e-2)---def test_build_tree_rows_window():- block_size = 16- table = torch.arange(1, 9, dtype=torch.int32, device=DEV)[None].repeat(1, 1)- committed = torch.tensor([50], dtype=torch.int32, device=DEV)- ancestors = torch.tensor([[[900, 901], [900, 902]]], dtype=torch.int32, device=DEV) # bs=1, K=2, depth=2- keys = torch.zeros(2, 64, dtype=torch.int32, device=DEV)- num_keys = torch.zeros(2, dtype=torch.int32, device=DEV)- build_tree_rows(table, block_size, committed, ancestors, keys, num_keys, step=2, window=10)- # the query at position 51 sees positions 42..51: 8 committed keys (42..49) and its 2 ancestors (50, 51)- assert num_keys.tolist() == [10, 10]- want = [int(table[0, p // block_size]) * block_size + p % block_size for p in range(42, 50)]- assert keys[0, :10].tolist() == want + [900, 901]- assert keys[1, :10].tolist() == want + [900, 902]--@pytest.mark.parametrize("slot_major", [False, True]) # the order of slots and heads in memory@pytest.mark.parametrize("blocks_per_table_block", [1, 4]diff --git a/tests/test_tree_step_attention.py b/tests/test_tree_step_attention.pyindex 5b0b4ea..7eea98b 100644--- a/tests/test_tree_step_attention.py+++ b/tests/test_tree_step_attention.py@@ -1,8 +1,7 @@# Copyright 2026 Eagle AI Corp.# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available-"""A draft step's shared-key attention (:func:`tree_step_attention`) against the per-row path it replaces-(:func:`build_tree_rows` + :func:`row_attention`) and a dense torch reference."""+"""A draft step's shared-key attention (:func:`tree_step_attention`) against a dense torch reference."""import pytestimport torch@@ -40,28 +39,27 @@ def _case(bs, top_k, heads, d, step, committed, window, cache_block=16, per_tabl[(1, 1, [70], 0), (2, 3, [5, 200], 0), (1, 4, [300], 100), (2, 2, [129, 64], 64)],)@pytest.mark.parametrize("group_size", [1, 2, 4, 8])-def test_tree_step_attention_matches_the_per_row_kernel(bs, step, committed, window, group_size):- from eagle_harness.vllm.draft_attention import build_tree_rows, row_attention, tree_step_attention+def test_tree_step_attention_matches_dense_torch(bs, step, committed, window, group_size):+ from eagle_harness.vllm.draft_attention import tree_step_attentiontop_k, heads, d = 4, 8, 64kv_heads = heads // group_sizeq, kv, table, table_block, committed_t, ancestors = _case(bs, top_k, heads, d, step, committed, window, kv_heads=kv_heads)- keys = torch.zeros(bs * top_k, 512, dtype=torch.int32, device=DEV)- num_keys = torch.zeros(bs * top_k, dtype=torch.int32, device=DEV)- build_tree_rows(table, table_block, committed_t, ancestors, keys, num_keys, step=step, window=window)- want = row_attention(q, kv, keys, num_keys, d**-0.5)got = tree_step_attention(q, kv, table, table_block, committed_t, ancestors, d**-0.5, step=step, window=window)- torch.testing.assert_close(got.float(), want.float(), atol=2e-2, rtol=2e-2)- # dense reference of one row: the last row of the last request- r = bs * top_k - 1- n = int(num_keys[r])- slots = keys[r, :n].long()- flat = kv.reshape(-1, kv_heads, 2 * d)[slots].repeat_interleave(group_size, dim=1)- scores = torch.einsum("hd,khd->hk", q[r].float(), flat[..., :d].float()) * d**-0.5- dense = torch.einsum("hk,khd->hd", scores.softmax(-1), flat[..., d:].float())- torch.testing.assert_close(got[r].float(), dense, atol=2e-2, rtol=2e-2)+ 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+ c = committed[b]+ start = min(max(0, c + step - window), c) if window else 0+ prefix = [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+ slots = torch.tensor(prefix + ancestors[b, lane, :step].tolist(), device=DEV)+ scores = torch.einsum("hd,khd->hk", q[r].float(), flat[slots, :, :d]) * d**-0.5+ dense = torch.einsum("hk,khd->hd", scores.softmax(-1), flat[slots, :, d:])+ torch.testing.assert_close(got[r].float(), dense, atol=2e-2, rtol=2e-2)@needs_triton@@ -136,11 +134,9 @@ def test_shared_rows_gqa_matches_torch_and_repeated_mha(group_size, packed, step@needs_triton@pytest.mark.parametrize("kv_heads", [0, 3, 16])def test_rows_reject_nonintegral_query_groups(kv_heads):- from eagle_harness.vllm.draft_attention import row_attention, tree_step_attention+ from eagle_harness.vllm.draft_attention import tree_step_attentionq, cache, table, table_block, lengths, ancestors = _case(1, 4, 8, 64, 1, [70], 0)invalid = torch.empty(cache.shape[0], cache.shape[1], kv_heads, cache.shape[3], device=DEV)with pytest.raises(ValueError, match="must be divisible"):tree_step_attention(q, invalid, table, table_block, lengths, ancestors, 0.125, step=1, window=0)- with pytest.raises(ValueError, match="must be divisible"):- row_attention(q, invalid, table, lengths, 0.125)