Official Inference Code of EAGLE-4
fix(sglang): compile first-use kernels at startup and keep slow rounds out of live costs
Seyfal Sultanovc88d32d4dc1b
diff --git a/docs/calibration.md b/docs/calibration.mdindex 836413b..8d4ab3c 100644--- a/docs/calibration.md+++ b/docs/calibration.md@@ -8,17 +8,27 @@ last_verified: 2026-10-20## Costs measured on the served rounds+On CUDA, startup warms the fused single-request tree acceptance kernels and the engine's draft softmax using+the served vocabulary size. Tree widths and depths up to 32 share the warmed acceptance programs. Larger shapes+and other engine kernels may still compile on first use; startup warm-up is not a guarantee of stall-free requests.+On SGLang the cost-model modes need no offline step. Without `data_path`, a matching packaged MI355X profileis selected when available. Otherwise, the server prices the draft step and target verify on its own served rounds. The first rounds at each batch bucket (a captured graph batch size) forceevery captured verify width a few times, timed with CUDA events around the exact kernels served at the realcontext length; after that every round refines its cell (an exponential moving average per batch bucket, verify-width and 1024-token context interval) and the cost model reads the resulting tables. The cells are cached under+width and 1024-token context interval) and the cost model reads the resulting tables. A cell's value starts as the+fastest of its first samples, and a later sample counts at most twice the cell's value, so a single slow round+(for example a kernel compiled on first use) moves a cell by a few percent and a lasting change still converges.+Until a new context interval has those first samples, it is priced from the nearest interval that has them.+If the initial seed samples span several intervals and none is fully seeded yet, their minimum supplies the price.+The cells are cached under`cost_cache` (default `~/.cache/eagle-harness/costs/<key>.json`), keyed by GPU name, TP size, the target's and thedraft's `config.json` digests, the engine version and the dtype, so a restart on the same setup starts with thecosts it ended with and a different setup measures again. All TP ranks decide from rank 0's cells.The live cache also checks the draft top-k and depth, because they change the work being timed. Invalid or-unreadable caches are ignored and remeasured. Cached and refreshed curves outside the cost model's supported+unreadable caches are ignored and remeasured, and so are caches written by eagle-harness 0.1.0, once, after an+upgrade. Cached and refreshed curves outside the cost model's supportedratios keep the fixed-shape policy until usable measurements arrive; they do not fail the next decode round.Seeding is bounded by the captured widths and sample count, not a wall-clock deadline, and occurs on servedrounds (including engine warmup requests), not during graph capture. Live timings alone do not establishdiff --git a/eagle_harness/core/live_costs.py b/eagle_harness/core/live_costs.pyindex 698a971..e8dd41d 100644--- a/eagle_harness/core/live_costs.py+++ b/eagle_harness/core/live_costs.py@@ -7,8 +7,11 @@ Offline calibration prices the draft step and the target verify on dummy batchessize, model pair, engine build and dtype. :class:`LiveCosts` prices them on the engine's own served roundsinstead: a seed sweep forces each captured verify width for a few rounds per batch bucket (the exact kernelsserved, at the real context), then every served round refines its cell (an EMA per batch bucket, verify width-and context interval). The cells become the same :class:`~eagle_harness.core.cost_table.BatchCostTable` objects-the :class:`~eagle_harness.core.cost_model.CostModel` reads, so the decision code has one input.+and context interval). A cell's value is the fastest of its first samples, and a later sample enters the EMA at+most at :data:`OUTLIER_RATIO` times the cell, so one stalled round (a kernel compiled on first use, a host+hiccup) moves a cell by a few percent at most and a lasting change still converges. The cells become the same+:class:`~eagle_harness.core.cost_table.BatchCostTable` objects the :class:`~eagle_harness.core.cost_model.CostModel`+reads, so the decision code has one input.A :class:`CostKey` names the setup the costs belong to. Offline tables carry it in ``key.json`` under their``data_path``; live costs carry it in their cache file. Costs whose key differs from the server's are refused@@ -107,6 +110,12 @@ def check_key(data_path: str, key: CostKey) -> None:# ------------------------------------------------------------------ live cells+# Cache files written under another rule for the cells are measured again.+CACHE_VERSION = 2+# A refining sample counts at most at this multiple of its cell.+OUTLIER_RATIO = 2.0++@dataclassclass Cell:"""One timed shape: microseconds (min of the seed samples, then an EMA) and the sample count."""@@ -166,18 +175,19 @@ class LiveCosts:if cell.samples < self.seed_samples:cell.us = us if cell.samples == 0 else min(cell.us, us)else:- cell.us += self.alpha * (us - cell.us)+ cell.us += self.alpha * (min(us, OUTLIER_RATIO * cell.us) - cell.us)cell.samples += 1# ---------------------------------------------------------------- tablesdef _value(self, bucket: int, width: int, interval: int) -> Optional[float]:- """The cell's cost, from the nearest measured interval when this one has no sample."""+ """Use the nearest fully seeded interval, or the pooled seed minimum if none is fully seeded yet."""for d in range(self.context_intervals):for i in (interval - d, interval + d):cell = self.cells.get((bucket, width, i))- if cell is not None and cell.samples:+ if cell is not None and cell.samples >= self.seed_samples:return cell.us- return None+ # Seeding counts samples across intervals; crossing a boundary must still discard a first-use stall.+ return min((c.us for (b, w, _), c in self.cells.items() if b == bucket and w == width and c.samples), default=None)def tables(self) -> Dict[int, BatchCostTable]:"""One table per ready bucket (the cost model's input), from the current cells."""@@ -209,6 +219,7 @@ class LiveCosts:def to_dict(self) -> dict:"""The cells and key as JSON data."""return {+ "version": CACHE_VERSION,"key": None if self.key is None else self.key.to_dict(),"draft_shape": list(self.draft_shape),"context_step": self.context_step,@@ -233,7 +244,8 @@ class LiveCosts:raise ValueError("expected an object")key = None if data.get("key") is None else CostKey.from_dict(data["key"])if (- key != self.key or data.get("draft_shape") != list(self.draft_shape)+ data.get("version") != CACHE_VERSION+ or key != self.key or data.get("draft_shape") != list(self.draft_shape)or (data["context_step"], data["context_intervals"]) != (self.context_step, self.context_intervals)):logger.info("Live cost cache %s is for another setup; measuring again.", path)diff --git a/eagle_harness/kernels/accept_tail.py b/eagle_harness/kernels/accept_tail.pyindex 1a34bc0..d9cac23 100644--- a/eagle_harness/kernels/accept_tail.py+++ b/eagle_harness/kernels/accept_tail.py@@ -11,6 +11,10 @@ is the walk and all of the index and token bookkeeping in one program;verify's hidden states) to the front. Both reproduce sglang's results exactly(``verify_tree_greedy``, ``fill_bonus_tokens``, ``assign_extend_cache_locs``,``fill_accept_out_cache_loc`` and ``_compact_accept_to_front``).++The tree width and depth are runtime arguments, so one compiled program serves every verify shape of a+process (up to :data:`LANES` nodes and levels): a new shape chosen by the cost model never compiles a kernel+inside a served round, and :func:`warm_up` compiles both kernels at startup."""from __future__ import annotations@@ -22,6 +26,14 @@ import tritonimport triton.language as tl+# Lanes of the index vectors: one warp, so every tree up to 32 nodes and 32 levels shares one program.+LANES = 32+++def _lanes(n: int) -> int:+ return max(triton.next_power_of_2(n), LANES)++class Accepted(NamedTuple):"""What a greedy tree verify of one request accepted."""@@ -34,7 +46,13 @@ class Accepted(NamedTuple):accepted_slots: torch.Tensor # int64 [depth]: KV slots they were written to by the verify (0 past accept_lens)+ do_not_specialize=["req_stride", "width", "depth"],+ do_not_specialize_on_alignment=[+ "target_ptr", "candidates_ptr", "retrieve_index_ptr", "retrieve_next_token_ptr", "retrieve_next_sibling_ptr",+ "seq_lens_ptr", "out_cache_loc_ptr", "req_to_token_ptr", "req_pool_idx_ptr",+ ],+)def _accept_tail_kernel(target_ptr,candidates_ptr,@@ -53,13 +71,13 @@ def _accept_tail_kernel(bonus_ptr,committed_slots_ptr,accepted_slots_ptr,- WIDTH: tl.constexpr,- DEPTH: tl.constexpr,+ width,+ depth,WIDTH_P2: tl.constexpr,DEPTH_P2: tl.constexpr,):ds = tl.arange(0, DEPTH_P2)- tl.store(accept_index_ptr + ds, -1, mask=ds < DEPTH)+ tl.store(accept_index_ptr + ds, -1, mask=ds < depth)tl.debug_barrier()# The tree walk: at each level take the first child of the last accepted node whose token is the@@ -69,12 +87,12 @@ def _accept_tail_kernel(cur = last * 0num = last * 0active = last * 0 + 1- for level in range(1, DEPTH):+ for level in range(1, depth):if active != 0:cur = tl.load(retrieve_next_token_ptr + cur)target_token = tl.load(target_ptr + last)found = last * 0- for sibling in range(WIDTH):+ for sibling in range(width):if found == 0:valid = cur != -1safe = tl.where(valid, cur, 0)@@ -96,22 +114,22 @@ def _accept_tail_kernel(# The predictions, the accepted path moved to the front (padding: node 0, which is always accepted).nodes = tl.arange(0, WIDTH_P2)- head = nodes < DEPTH+ head = nodes < depthpath = tl.load(accept_index_ptr + nodes, mask=head, other=-1).to(tl.int64)head_value = tl.load(target_ptr + tl.maximum(path, 0), mask=head, other=0)- accepted = tl.load(accept_index_ptr + ds, mask=(ds <= num) & (ds < DEPTH), other=-1).to(tl.int64)+ accepted = tl.load(accept_index_ptr + ds, mask=(ds <= num) & (ds < depth), other=-1).to(tl.int64)on_path = tl.sum((nodes[:, None] == accepted[None, :]).to(tl.int32), axis=1) > 0- tail_value = tl.where(on_path, tl.load(target_ptr + nodes, mask=nodes < WIDTH, other=0), 0)- tl.store(predict_ptr + nodes, tl.where(head, head_value, tail_value).to(tl.int32), mask=nodes < WIDTH)+ tail_value = tl.where(on_path, tl.load(target_ptr + nodes, mask=nodes < width, other=0), 0)+ tl.store(predict_ptr + nodes, tl.where(head, head_value, tail_value).to(tl.int32), mask=nodes < width)# The KV slots to move: the request's next free slots, and where the verify wrote the accepted tokens.row = tl.load(req_pool_idx_ptr).to(tl.int64)- keep = (ds <= num) & (ds < DEPTH)- path = tl.load(accept_index_ptr + ds, mask=ds < DEPTH, other=-1).to(tl.int64)+ keep = (ds <= num) & (ds < depth)+ path = tl.load(accept_index_ptr + ds, mask=ds < depth, other=-1).to(tl.int64)committed = tl.load(req_to_token_ptr + row * req_stride + seq_len + ds, mask=keep, other=0)- tl.store(committed_slots_ptr + ds, committed.to(tl.int64), mask=ds < DEPTH)+ tl.store(committed_slots_ptr + ds, committed.to(tl.int64), mask=ds < depth)accepted_slot = tl.load(out_cache_loc_ptr + path, mask=keep, other=0)- tl.store(accepted_slots_ptr + ds, accepted_slot.to(tl.int64), mask=ds < DEPTH)+ tl.store(accepted_slots_ptr + ds, accepted_slot.to(tl.int64), mask=ds < depth)def accept_tail(@@ -160,16 +178,16 @@ def accept_tail(out.bonus_tokens,out.committed_slots,out.accepted_slots,- WIDTH=width,- DEPTH=depth,- WIDTH_P2=triton.next_power_of_2(width),- DEPTH_P2=triton.next_power_of_2(depth),+ width,+ depth,+ WIDTH_P2=_lanes(width),+ DEPTH_P2=_lanes(depth),num_warps=1,)return out[email protected](do_not_specialize=["depth"])def _compact_rows_kernel(src_ptr,dst_ptr,@@ -177,13 +195,13 @@ def _compact_rows_kernel(src_stride,dst_stride,cols,- DEPTH: tl.constexpr,+ depth,BLOCK: tl.constexpr,):row = tl.program_id(0)offsets = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)- path = tl.load(accept_index_ptr + tl.minimum(row, DEPTH - 1)).to(tl.int64)- source = tl.where(row < DEPTH, tl.maximum(path, 0), row)+ path = tl.load(accept_index_ptr + tl.minimum(row, depth - 1)).to(tl.int64)+ source = tl.where(row < depth, tl.maximum(path, 0), row)values = tl.load(src_ptr + source * src_stride + offsets, mask=offsets < cols)tl.store(dst_ptr + row.to(tl.int64) * dst_stride + offsets, values, mask=offsets < cols)@@ -201,6 +219,31 @@ def compact_rows(elif out.shape != rows.shape or out.stride(1) != 1 or out.data_ptr() == rows.data_ptr():raise ValueError("compact_rows needs an out of the rows' shape, unit column stride, not the rows")_compact_rows_kernel[(width, triton.cdiv(cols, block))](- rows, out, accept_index, rows.stride(0), out.stride(0), cols, DEPTH=accept_index.shape[1], BLOCK=block+ rows, out, accept_index, rows.stride(0), out.stride(0), cols, accept_index.shape[1], BLOCK=block)return out+++def warm_up(hidden_rows: torch.Tensor, hidden_dtype: torch.dtype) -> None:+ """Compile :func:`accept_tail` and :func:`compact_rows` for a server before it serves.++ ``hidden_rows`` is the buffer the served compaction writes (``[rows >= 2, cols]``; its first two rows are+ overwritten) and ``hidden_dtype`` the dtype of the verify's hidden states it reads. The other served inputs+ are int64 (target tokens, tree tables, lengths, KV slots) and an int32 ``req_to_token``, as here.+ """+ long = dict(dtype=torch.int64, device=hidden_rows.device)+ tokens = torch.zeros(2, **long)+ tables = torch.tensor([[1, -1]], **long)+ accepted = accept_tail(+ tokens,+ tokens,+ torch.arange(2, **long).reshape(1, 2),+ tables,+ tables,+ torch.ones(1, **long),+ tokens,+ torch.zeros(1, 4, dtype=torch.int32, device=hidden_rows.device),+ torch.zeros(1, **long),+ 2,+ )+ compact_rows(torch.zeros_like(hidden_rows[:2], dtype=hidden_dtype), accepted.accept_index, out=hidden_rows[:2])diff --git a/eagle_harness/sglang/worker.py b/eagle_harness/sglang/worker.pyindex 967cc1c..f422c93 100644--- a/eagle_harness/sglang/worker.py+++ b/eagle_harness/sglang/worker.py@@ -52,10 +52,12 @@ from sglang.srt.speculative.draft_utils import DraftBackendFactoryfrom sglang.srt.speculative.eagle_utils import default_tree_mask_modefrom sglang.srt.speculative.eagle_worker_common import run_eagle_verifyfrom sglang.srt.speculative.eagle_worker_v2 import EagleDraftWorker, EAGLEWorkerV2+from sglang.srt.speculative import spec_utilsfrom sglang.srt.speculative.spec_utils import draft_tp_context, spec_stage_spanfrom sglang.version import __version__ as sglang_versionfrom eagle_harness.core.chain_width import chain_widths+from eagle_harness.kernels.accept_tail import warm_up as warm_up_accept_tailfrom eagle_harness.core.config import HarnessConfig, Mode, build_cost_model, parse_harness_configfrom eagle_harness.core.cost_model import CostModel, FixedShapePolicyfrom eagle_harness.core.limits import ComputeIntensity@@ -165,6 +167,21 @@ class HarnessDraftWorker(EagleDraftWorker):widths=lambda bs: verify_widths(bs, intensity, width),)self.tree_mask_mode = default_tree_mask_mode()+ self._warm_up_kernels()++ def _warm_up_kernels(self) -> None:+ """Compile, before serving, the kernels whose first use would otherwise stall a served round: the fused+ accept step (batch-size-1 trees) and the softmax of sglang's draft extend after a prefill (a JIT module).+ """+ if torch.device(self.device).type != "cuda":+ return+ if self.topk > 1:+ warm_up_accept_tail(self.extend.hidden_rows(2), self.target_worker.model_runner.dtype)+ softmax = getattr(spec_utils, "sampling_softmax", None)+ if softmax is not None:+ # The engine dispatches by vocabulary size; a tiny tensor can warm a different backend.+ vocab_size = self.draft_runner.model.logits_processor.vocab_size+ softmax(torch.zeros(1, vocab_size, dtype=torch.float32, device=self.device))def _capture_cuda_graphs(self) -> None:self.cuda_graph_runner = Nonediff --git a/tests/test_accept_tail_gpu.py b/tests/test_accept_tail_gpu.pyindex ac654ff..1bc0e01 100644--- a/tests/test_accept_tail_gpu.py+++ b/tests/test_accept_tail_gpu.py@@ -17,7 +17,8 @@ from sglang.srt.speculative.eagle_utils import verify_tree_greedy_func # noqa:from sglang.srt.speculative.eagle_worker_common import _compact_accept_to_front # noqa: E402from sglang.srt.speculative.spec_utils import assign_extend_cache_locs # noqa: E402-from eagle_harness.kernels.accept_tail import accept_tail, compact_rows # noqa: E402+from eagle_harness.kernels import accept_tail as accept_tail_module # noqa: E402+from eagle_harness.kernels.accept_tail import accept_tail, compact_rows, warm_up # noqa: E402def _tree(width, rng):@@ -120,6 +121,38 @@ def test_compact_rows_matches_sglang(cols):assert torch.equal(compact_rows(rows, accept_index), expected)+def _compiled(kernel) -> int:+ return len(kernel.device_caches[torch.cuda.current_device()][0])+++def test_warm_up_compiles_the_one_program_every_served_shape_runs():+ """After the startup warm-up, no verify width or depth up to 32 compiles a kernel in a served round."""+ hidden = torch.zeros(64, 5120, dtype=torch.bfloat16, device="cuda")+ warm_up(hidden, torch.bfloat16)+ kernels = (accept_tail_module._accept_tail_kernel, accept_tail_module._compact_rows_kernel)+ before = [_compiled(k) for k in kernels]+ rng = random.Random(7)+ long = dict(dtype=torch.int64, device="cuda")+ for width, depth in ((16, 12), (9, 8), (4, 4), (2, 2), (31, 12), (32, 32), (8, 1)):+ candidates, next_token, next_sibling, target = _tree(width, rng)+ accepted = accept_tail(+ torch.tensor(target, **long),+ torch.tensor(candidates, **long),+ torch.arange(width, **long).reshape(1, width),+ torch.tensor(next_token, **long).reshape(1, width),+ torch.tensor(next_sibling, **long).reshape(1, width),+ torch.tensor([rng.randrange(1, 150)], **long),+ torch.randint(1, 1 << 20, (width + 1,), **long)[1:], # 8-byte aligned, as a slice of a slot list can be+ torch.randint(1, 1 << 20, (3, 200 + width), dtype=torch.int32, device="cuda"),+ torch.tensor([1], **long),+ depth,+ )+ rows = torch.randn(width, 5120, device="cuda").to(torch.bfloat16)+ compact_rows(rows, accepted.accept_index, out=hidden[:width])+ torch.cuda.synchronize()+ assert [_compiled(k) for k in kernels] == before++def test_tail_graphs_run_a_non_idempotent_body_once_per_round():"""First round eager, second captured and replayed, later ones replayed: each round runs the body once."""from eagle_harness.sglang.verify_step import AcceptTailGraphsdiff --git a/tests/test_live_costs.py b/tests/test_live_costs.pyindex f0650fd..b7cdad3 100644--- a/tests/test_live_costs.py+++ b/tests/test_live_costs.py@@ -116,6 +116,55 @@ def test_cache_reseeds_when_the_draft_step_shape_changes(tmp_path):assert not changed.load(path) and not changed.cells+def test_one_stalled_round_moves_a_seeded_cell_by_a_few_percent_at_most():+ live = _live(alpha=0.05)+ _seed(live, 1, {1: 3000.0, 16: 3464.0, 8: 3200.0, 32: 4000.0, 64: 5000.0})+ cell = live.cells[(1, 16, 0)]+ live.record(1, 16, 500, 320_000.0) # a kernel compiled inside the round+ assert 3464.0 < cell.us <= 3464.0 * 1.05+ assert live.tables()[1].intervals[0].target.value[2] == cell.us+++def test_a_lasting_change_still_converges():+ live = _live(alpha=0.05)+ _seed(live, 1, {1: 3000.0, 16: 3464.0, 8: 3200.0, 32: 4000.0, 64: 5000.0})+ for _ in range(200):+ live.record(1, 16, 500, 3 * 3464.0)+ assert live.cells[(1, 16, 0)].us == pytest.approx(3 * 3464.0, rel=0.01)+ for _ in range(200):+ live.record(1, 16, 500, 2000.0)+ assert live.cells[(1, 16, 0)].us == pytest.approx(2000.0, rel=0.01)+++def test_a_new_interval_is_priced_from_a_seeded_one_until_it_has_seed_samples():+ live = _live()+ _seed(live, 1, {1: 3000.0, 16: 3464.0, 8: 3200.0, 32: 4000.0, 64: 5000.0}, context=500)+ far = live.interval(6000)+ live.record(1, 16, 6000, 320_000.0) # the interval's first sample stalls+ assert live.tables()[1].intervals[far].target.value[2] == 3464.0+ live.record(1, 16, 6000, 3600.0) # seed_samples=2: the interval's own minimum takes over+ assert live.tables()[1].intervals[far].target.value[2] == 3600.0+++def test_seed_samples_split_across_intervals_do_not_publish_one_stall():+ live = _live()+ _seed(live, 1, {1: 3000.0, 8: 3200.0, 32: 4000.0, 64: 5000.0})+ live.record(1, 16, 2000, 320_000.0)+ live.record(1, 16, 2100, 3464.0) # seed sweep crosses the context-interval boundary+ assert live.ready(1)+ assert all(interval.target.value[2] == 3464.0 for interval in live.tables()[1].intervals)+++def test_cache_of_another_cell_rule_is_measured_again(tmp_path):+ live = _live()+ _seed(live, 1, {1: 4000.0, 64: 7200.0, 32: 5700.0, 16: 4800.0, 8: 4500.0})+ path = tmp_path / "costs.json"+ data = live.to_dict()+ del data["version"] # written before the outlier rule+ path.write_text(json.dumps(data))+ assert not _live().load(str(path))++@pytest.mark.parametrize("us", [float("nan"), float("inf"), -1.0, 0.0])def test_nonfinite_or_nonpositive_timings_do_not_seed_a_bucket(us):live = _live()diff --git a/tests/test_sglang_sampled_worker.py b/tests/test_sglang_sampled_worker.pyindex f6428d9..d1c4800 100644--- a/tests/test_sglang_sampled_worker.py+++ b/tests/test_sglang_sampled_worker.py@@ -71,6 +71,31 @@ def test_draft_worker_built_like_sglang_seeds_the_sampled_tree_only_with_the_hooassert draft.steps is steps # every sglang-built draft worker has its DraftSteps before the first round[email protected]("vocab_size", [32, 128256, 248320])+def test_startup_softmax_uses_the_served_vocabulary(monkeypatch, vocab_size):+ """Shape-based backend dispatch must see the same vocabulary during warm-up and serving."""+ worker = SimpleNamespace(+ device="cuda", topk=1,+ draft_runner=SimpleNamespace(model=SimpleNamespace(logits_processor=SimpleNamespace(vocab_size=vocab_size))),+ )+ zeros = torch.zeros+ allocations, calls = [], []++ def allocate(*shape, dtype, device):+ allocations.append((shape, dtype, device))+ return zeros(*shape, dtype=dtype)++ def softmax(logits):+ calls.append((tuple(logits.shape), logits.dtype))+ return logits.softmax(dim=-1)++ monkeypatch.setattr(worker_mod.torch, "zeros", allocate)+ monkeypatch.setattr(worker_mod.spec_utils, "sampling_softmax", softmax)+ worker_mod.HarnessDraftWorker._warm_up_kernels(worker)+ assert allocations == [((1, vocab_size), torch.float32, "cuda")]+ assert calls == [((1, vocab_size), torch.float32)]++@pytest.mark.parametrize("engine_verify, active", [(_verify_without_hook, False), (_verify_with_hook, False), (_verify_with_hook, True)])def test_verify_passes_the_tree_sampler_only_for_an_active_sampled_tree(monkeypatch, engine_verify, active):monkeypatch.setattr(worker_mod, "run_eagle_verify", engine_verify)