Official Inference Code of EAGLE-4
perf(sglang): sample temperature-1 trees from recorded proposals in one fused draw
Seyfal Sultanov061a1d28e507
diff --git a/eagle_harness/core/sampled_tree.py b/eagle_harness/core/sampled_tree.pynew file mode 100644index 0000000..7370721--- /dev/null+++ b/eagle_harness/core/sampled_tree.py@@ -0,0 +1,103 @@+# Copyright 2026 Eagle AI Corp.+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available+"""Ordered proposals and recursive rejection without replacement.++Proposal probabilities are recorded before drawing; after each rejection q+is conditioned on the earlier draws. Subtract the *whole* conditional q from+p, not just the rejected token. This implements the probability recursion of+Recursive Speculative Decoding (Jeon et al., arXiv:2402.14160), independently+of any engine implementation.+"""++from typing import NamedTuple, Optional++import torch+++class ChildProposals(NamedTuple):+ """One expanded parent's sparse proposal distribution and ordered draws.++ ``scores`` are descending order statistics of q, NOT the probabilities of+ the sampled tokens. A planner may use them without inspecting a child's+ own draw. Selection must retain a prefix of each parent's draw order.+ Candidate ids must be distinct, valid vocabulary ids; zero q is allowed.+ """++ probs: torch.Tensor # [rows, candidates]+ token_ids: torch.Tensor # [rows, candidates]+ positions: torch.Tensor # [rows, children], indices into the candidate row+ tokens: torch.Tensor # [rows, children], global vocabulary ids+ scores: torch.Tensor # [rows, children], sample-independent rank scores+++class RejectionResult(NamedTuple):+ tokens: torch.Tensor # [rows], accepted child or residual draw+ accepted_position: torch.Tensor # [rows], draw index, or -1 for a residual draw+++def draw_children(+ logits: torch.Tensor,+ token_ids: torch.Tensor,+ count: int,+ *,+ generator: Optional[torch.Generator] = None,+ uniforms: Optional[torch.Tensor] = None,+) -> ChildProposals:+ """Gumbel-top-k ordered draws from finite, nonempty candidate distributions.++ ``logits`` already include the chosen proposal temperature/filters. The+ target need not have the same support or distribution. Slots after the+ nonzero support are inert (score zero), never valid proposals.+ """+ if logits.ndim != 2 or token_ids.shape != logits.shape or not 1 <= count <= logits.shape[1]:+ raise ValueError("expected matching [rows, candidates] logits/ids and count within the candidate width")+ probs = torch.softmax(logits.float(), dim=-1)+ if uniforms is None:+ uniforms = torch.rand(probs.shape, dtype=probs.dtype, device=probs.device, generator=generator)+ # rand is [0, 1); clamping only its possible zero avoids log(0).+ keys = probs.log() - (-uniforms.clamp_min(torch.finfo(probs.dtype).tiny).log()).log()+ positions = keys.topk(count, dim=-1).indices+ return ChildProposals(probs, token_ids, positions, token_ids.gather(1, positions), probs.topk(count, dim=-1).values)+++def reject_children(+ target_probs: torch.Tensor,+ proposals: ChildProposals,+ uniforms: torch.Tensor,+ final_uniforms: torch.Tensor,+) -> RejectionResult:+ """Reference batched recursive rejection for one parent's retained prefix.++ Target rows are normalized, and uniforms are independent of the proposals+ and each other, in [0, 1). Float64 arithmetic makes this a numerical oracle+ for the GPU implementation. It is not the serving implementation.+ """+ rows, vocab = target_probs.shape+ count = proposals.positions.shape[1]+ if uniforms.shape != (rows, count) or final_uniforms.shape != (rows,):+ raise ValueError("accept coins must match the draws, with one final coin per target row")+ residual = target_probs.double().clone()+ q = proposals.probs.double().clone()+ chosen = torch.full((rows,), -1, dtype=torch.int64, device=target_probs.device)+ tokens = torch.zeros(rows, dtype=torch.int64, device=target_probs.device)+ for child in range(count):+ index = proposals.positions[:, child : child + 1]+ token = proposals.tokens[:, child : child + 1]+ mass = residual.sum(dim=-1, keepdim=True)+ q_mass = q.sum(dim=-1, keepdim=True)+ conditional = q / q_mass.clamp_min(torch.finfo(q.dtype).tiny)+ q_y = conditional.gather(1, index).flatten()+ p_y = residual.gather(1, token).flatten()+ accept = (chosen == -1) & (q_y > 0) & (uniforms[:, child] * mass.flatten() * q_y < p_y)+ chosen = torch.where(accept, child, chosen)+ tokens = torch.where(accept, token.flatten(), tokens)+ full_q = torch.zeros((rows, vocab), dtype=residual.dtype, device=residual.device)+ full_q.scatter_(1, proposals.token_ids, conditional)+ updated = (residual - mass * full_q).clamp_min(0)+ residual = torch.where((chosen == -1)[:, None], updated, residual)+ q.scatter_(1, index, 0)+ cdf = residual.cumsum(dim=-1)+ threshold = final_uniforms.double() * cdf[:, -1]+ bonus = torch.searchsorted(cdf.contiguous(), threshold[:, None].contiguous(), right=True).flatten()+ # Accepted rows do not consume a residual draw (it can be all zero there).+ return RejectionResult(torch.where(chosen == -1, bonus.clamp_max(vocab - 1), tokens), chosen)diff --git a/eagle_harness/kernels/candidate_ops.py b/eagle_harness/kernels/candidate_ops.pyindex c231295..5f66366 100644--- a/eagle_harness/kernels/candidate_ops.py+++ b/eagle_harness/kernels/candidate_ops.py@@ -197,8 +197,8 @@ def candidate_head(all_gather: Callable[[torch.Tensor], torch.Tensor] | None = None,cuda_kernels: bool = True,max_triton_elements: int | None = None,-) -> tuple[torch.Tensor, torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:- """Candidate logits, ids and top-k probabilities for each row.+) -> tuple[torch.Tensor, torch.Tensor, tuple[torch.Tensor, torch.Tensor] | None]:+ """Candidate logits, ids and top-k probabilities for each row (None for ``top_k == 0``).``scores`` [rows, shard vocab] are this rank's low-rank scores (padding columns already masked), ``lm_head``[shard vocab, H] its exact weights. Shard top-k, exact re-scoring (:func:`gather_dot`), the candidate tail; under TP@@ -219,10 +219,7 @@ def candidate_head(else:ranks = all_gather(gather_dot_packed(lm_head, local_ids, hidden, vocab_start))logits, tokens = ranks[..., :num_candidates].view(torch.float32), ranks[..., num_candidates:]- logits, tokens, ranked = candidate_tail(logits, tokens, rows, top_k, cuda_kernels=cuda_kernels)- if ranked is None:- raise ValueError("candidate_head requires top_k > 0")- return logits, tokens, ranked+ return candidate_tail(logits, tokens, rows, top_k, cuda_kernels=cuda_kernels)def candidate_topk(diff --git a/eagle_harness/kernels/sampled_draw.py b/eagle_harness/kernels/sampled_draw.pynew file mode 100644index 0000000..6061277--- /dev/null+++ b/eagle_harness/kernels/sampled_draw.py@@ -0,0 +1,165 @@+# Copyright 2026 Eagle AI Corp.+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available+"""One-launch recorded-q proposal draw: softmax over the candidates, Gumbel-top-K children, q recorded in place.++Replaces the torch chain of :func:`eagle_harness.core.sampled_tree.draw_children` (softmax, rand, two logs, two+top-k, gather, five slice copies) and the per-step TP broadcast of its uniforms. The uniforms come from counter-based+Philox keyed by ``(seed, round, launch, element)``: every TP rank holds the same seed (sglang broadcasts+``random_seed``) and replays the same graphs, so every rank draws the same tree without a collective, as the+EAGLE-4 fork does. With ``uniforms`` given (tests), the draw equals :func:`draw_children`'s on the same uniforms.+"""++from __future__ import annotations++from typing import Optional, Tuple++import torch+import triton+import triton.language as tl+++def _sample_children(+ LOGITS,+ TOKENS,+ ROUND,+ UNIF,+ Q,+ QIDS,+ POS,+ OUT_TOKENS,+ SCORES,+ REQ,+ seed,+ launch,+ stride_l,+ stride_t,+ rows_per_req,+ q_batch_stride,+ q_slot,+ pos_batch_stride,+ pos_start,+ NC: tl.constexpr,+ K: tl.constexpr,+ BLOCK: tl.constexpr,+ USE_UNIFORMS: tl.constexpr,+):+ row = tl.program_id(0)+ req = row // rows_per_req+ local = row - req * rows_per_req+ store = tl.load(REQ + req) # the request's row in the recorded-q stores+ c = tl.arange(0, BLOCK)+ mask = c < NC+ logits = tl.load(LOGITS + row * stride_l + c, mask=mask, other=float("-inf")).to(tl.float32)+ tokens = tl.load(TOKENS + row * stride_t + c, mask=mask, other=0).to(tl.int64)+ peak = tl.max(logits, 0)+ e = tl.exp(logits - peak)+ e = tl.where(mask, e, 0.0)+ probs = e / tl.sum(e, 0)+ if USE_UNIFORMS:+ u = tl.load(UNIF + row * NC + c, mask=mask, other=0.5)+ else:+ rnd = tl.load(ROUND)+ element = (row * NC + c).to(tl.uint32)+ r0, _r1, _r2, _r3 = tl.philox(+ seed,+ element,+ tl.full((BLOCK,), rnd, tl.uint32),+ tl.full((BLOCK,), launch, tl.uint32),+ tl.zeros((BLOCK,), tl.uint32),+ )+ u = tl.uint_to_uniform_float(r0)+ # rand is [0, 1): clamping only its possible zero avoids log(0); matches draw_children.+ u = tl.maximum(u, 1.1754944e-38)+ keys = tl.log(probs) - tl.log(-tl.log(u))+ keys = tl.where(mask, keys, float("-inf"))+ qbase = Q + store * q_batch_stride + (q_slot + local) * NC+ tl.store(qbase + c, probs, mask=mask)+ tl.store(QIDS + store * q_batch_stride + (q_slot + local) * NC + c, tokens, mask=mask)+ pbase = POS + store * pos_batch_stride + pos_start + local * K+ ranked = tl.where(mask, probs, -1.0)+ for j in tl.static_range(K):+ best = tl.max(keys, 0)+ # the first index attaining the max (a tie needs equal fp keys; torch.topk's tie order is unspecified too)+ pos = tl.min(tl.where(keys == best, c, BLOCK), 0)+ tl.store(pbase + j, pos.to(tl.int64))+ token = tl.sum(tl.where(c == pos, tokens, 0), 0)+ tl.store(OUT_TOKENS + row * K + j, token)+ keys = tl.where(c == pos, float("-inf"), keys)+ # The planner's score is q's j-th order statistic, never the draw's own q (that would bias the pruning).+ top = tl.max(ranked, 0)+ tl.store(SCORES + row * K + j, top)+ first = tl.min(tl.where(ranked == top, c, BLOCK), 0)+ ranked = tl.where(c == first, -1.0, ranked)+++def sample_children(+ logits: torch.Tensor,+ token_ids: torch.Tensor,+ count: int,+ *,+ seed: int,+ launch: int,+ counter: torch.Tensor,+ q: torch.Tensor,+ q_ids: torch.Tensor,+ positions: torch.Tensor,+ slot: int,+ start: int,+ rows_per_req: int,+ uniforms: Optional[torch.Tensor] = None,+ req_index: Optional[torch.Tensor] = None,+) -> Tuple[torch.Tensor, torch.Tensor]:+ """Gumbel-top-``count`` ordered draws per row, recorded in place; returns ``(scores [rows, count] fp32, tokens+ [rows, count] i64)``.++ ``q``/``q_ids`` are ``[bs, slots, NC]`` stores: request ``b``'s row ``i`` (``i < rows_per_req``) is written at+ slot ``slot + i``. ``positions`` is ``[bs, nodes]``: child ``j`` of that row is written at ``start + i * count ++ j``. ``counter`` is a device int32 round counter (advanced by the caller at step 0); ``launch`` distinguishes the+ draws of one round. The scores are q's order statistics. ``req_index`` (int64 ``[bs]``) maps request ``b`` to its+ row in the stores (default: the batch position).+ """+ rows, nc = logits.shape+ if token_ids.shape != logits.shape or not 1 <= count <= nc or rows % rows_per_req:+ raise ValueError("expected matching [rows, candidates] logits/ids, count within the width, whole requests")+ bs = rows // rows_per_req+ if req_index is None:+ req_index = torch.arange(bs, dtype=torch.int64, device=logits.device)+ if q.shape != q_ids.shape or q.dim() != 3 or q.shape[1] < slot + rows_per_req or q.shape[2] != nc:+ raise ValueError("q store must be [bs, slots, candidates] with room for the written slots")+ if positions.dim() != 2 or positions.shape[0] != q.shape[0] or positions.shape[1] < start + rows_per_req * count:+ raise ValueError("positions must be [bs, nodes] with room for the written children")+ if not (q.is_contiguous() and q_ids.is_contiguous() and positions.is_contiguous()):+ raise ValueError("recorded-q stores must be contiguous")+ device = logits.device+ scores = torch.empty((rows, count), dtype=torch.float32, device=device)+ tokens = torch.empty((rows, count), dtype=torch.int64, device=device)+ if rows == 0:+ return scores, tokens+ _sample_children[(rows,)](+ logits,+ token_ids,+ counter,+ uniforms if uniforms is not None else logits,+ q,+ q_ids,+ positions,+ tokens,+ scores,+ req_index,+ int(seed) & 0xFFFFFFFF,+ int(launch),+ logits.stride(0),+ token_ids.stride(0),+ rows_per_req,+ q.stride(0),+ slot,+ positions.stride(0),+ start,+ NC=nc,+ K=count,+ BLOCK=triton.next_power_of_2(nc),+ USE_UNIFORMS=uniforms is not None,+ num_warps=4 if nc <= 256 else 8,+ )+ return scores, tokensdiff --git a/eagle_harness/kernels/sampled_tree.py b/eagle_harness/kernels/sampled_tree.pynew file mode 100644index 0000000..7c000a8--- /dev/null+++ b/eagle_harness/kernels/sampled_tree.py@@ -0,0 +1,164 @@+# Copyright 2026 Eagle AI Corp.+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available+"""Sparse-q recursive tree rejection; the host retains target filtering/commit."""++import torch+import triton+import triton.language as tl+++def _walk(+ P,+ Q,+ QIDS,+ POS,+ ROOT_VALID,+ NODES,+ TOKENS,+ INDEX,+ CHILD,+ SIBLING,+ COINS,+ PREDICT,+ PATH,+ LENGTH,+ FINAL_ROW,+ FINAL_IDS,+ FINAL_RESIDUAL,+ REQ,+ V: tl.constexpr,+ W: tl.constexpr,+ D: tl.constexpr,+ K: tl.constexpr,+ C: tl.constexpr,+ S: tl.constexpr,+ N: tl.constexpr,+ BLOCK: tl.constexpr,+):+ b = tl.program_id(0)+ store = tl.load(REQ + b) # the request's slot in the recorded-q stores (follows it across batch changes)+ c = tl.arange(0, BLOCK)+ current = tl.full((), 0, tl.int32)+ length = tl.full((), 1, tl.int32)+ running = tl.full((), 1, tl.int32)+ row = tl.load(INDEX + b * W)+ tl.store(PATH + b * D, row)+ # Entries beyond the accepted path are initialized by the launcher.+ while running != 0:+ child = tl.load(CHILD + b * W + current)+ raw = tl.load(NODES + b * (W - 1) + tl.maximum(child - 1, 0), mask=child >= 0, other=0)+ valid = (child >= 0) & ((current != 0) | tl.load(ROOT_VALID + store))+ slot = tl.where(raw < K, 0, 1 + (raw - K) // K)+ slot = tl.maximum(slot, 0)+ ids = tl.load(QIDS + (store * S + slot) * C + c, mask=(c < C) & valid, other=0)+ ids = tl.where(valid, ids, c)+ q = tl.load(Q + (store * S + slot) * C + c, mask=(c < C) & valid, other=0)+ residual = tl.load(P + row * V + ids, mask=c < C, other=0).to(tl.float32)+ outside = tl.maximum(1.0 - tl.sum(residual, 0), 0.0)+ found = tl.full((), 0, tl.int32)+ while (child >= 0) & valid & (found == 0) & (length < D):+ raw = tl.load(NODES + b * (W - 1) + child - 1)+ position = tl.load(POS + store * N + raw)+ qsum = tl.sum(q, 0)+ qconditional = q / tl.where(qsum > 0.0, qsum, 1.0)+ qy = tl.sum(tl.where(c == position, qconditional, 0.0), 0)+ py = tl.sum(tl.where(c == position, residual, 0.0), 0)+ mass = outside + tl.sum(residual, 0)+ coin = tl.load(COINS + b * W + child)+ accept = (qy > 0.0) & (py > 0.0) & (coin * mass * qy < py)+ if accept:+ token = tl.load(TOKENS + b * W + child)+ tl.store(PREDICT + row, token.to(tl.int32))+ current = child.to(tl.int32)+ row = tl.load(INDEX + b * W + child)+ tl.store(PATH + b * D + length, row.to(tl.int32))+ length += 1+ found = 1+ else:+ residual = tl.maximum(residual - mass * qconditional, 0.0)+ q = tl.where(c == position, 0.0, q)+ child = tl.load(SIBLING + b * W + child)+ if found == 0:+ running = 0+ tl.store(FINAL_ROW + b, row)+ tl.store(FINAL_IDS + b * C + c, ids, mask=c < C)+ tl.store(FINAL_RESIDUAL + b * C + c, residual, mask=c < C)+ tl.store(LENGTH + b, length)+++def sample_tree(+ target_probs,+ q,+ q_ids,+ positions,+ root_valid,+ nodes,+ tokens,+ retrieve_index,+ retrieve_next_token,+ retrieve_next_sibling,+ uniforms,+ final_uniforms,+ *,+ top_k,+ max_depth,+ req_index=None,+):+ """Return node-indexed predictions, accept lengths, and global accepted rows.++ q/ids are [B, expansion slots, candidates]; positions are [B, raw nodes].+ ``nodes`` maps non-root verify rows to raw draft nodes ([B, W - 1]).+ Siblings must retain an ordered prefix of the original draws. Every target+ row is normalized. All buffers are contiguous; vocabulary ids are valid.+ ``root_valid=False`` emits one target token, used when a prefill/batch change+ supplied deterministic roots without a recorded proposal distribution.+ ``req_index``: int64 ``[B]`` row of each request in ``q``/``q_ids``/``positions``/``root_valid`` (default: the+ batch position), so recorded proposals follow a request across batch changes.+ """+ bs, width, vocab = target_probs.shape+ slots, candidates = q.shape[1:]+ device = target_probs.device+ if req_index is None:+ req_index = torch.arange(bs, dtype=torch.int64, device=device)+ predict = torch.zeros(bs * width, dtype=torch.int32, device=device)+ path = torch.full((bs, max_depth), -1, dtype=torch.int32, device=device)+ lengths = torch.empty(bs, dtype=torch.int32, device=device)+ final_rows = torch.empty(bs, dtype=torch.int64, device=device)+ final_ids = torch.empty((bs, candidates), dtype=torch.int64, device=device)+ final_residual = torch.empty((bs, candidates), dtype=torch.float32, device=device)+ _walk[(bs,)](+ target_probs,+ q,+ q_ids,+ positions,+ root_valid,+ nodes,+ tokens,+ retrieve_index,+ retrieve_next_token,+ retrieve_next_sibling,+ uniforms,+ predict,+ path,+ lengths,+ final_rows,+ final_ids,+ final_residual,+ req_index,+ V=vocab,+ W=width,+ D=max_depth,+ K=top_k,+ C=candidates,+ S=slots,+ N=positions.shape[1],+ BLOCK=triton.next_power_of_2(candidates),+ )+ residual = target_probs.reshape(-1, vocab).index_select(0, final_rows)+ residual.scatter_(1, final_ids, final_residual)+ cdf = residual.cumsum(dim=-1)+ threshold = final_uniforms.reshape(bs, 1) * cdf[:, -1:]+ bonus = torch.searchsorted(cdf, threshold.contiguous(), right=True).flatten().clamp_max(vocab - 1)+ predict.scatter_(0, final_rows, bonus.to(torch.int32))+ return predict, lengths, pathdiff --git a/eagle_harness/sglang/draft_extend.py b/eagle_harness/sglang/draft_extend.pyindex 0b26df5..fde3242 100644--- a/eagle_harness/sglang/draft_extend.py+++ b/eagle_harness/sglang/draft_extend.py@@ -75,6 +75,7 @@ class DraftExtend:self.positions = torch.zeros(max_bs * width, dtype=i64, device=device)self.last = torch.zeros(max_bs, dtype=i64, device=device) # each request's row of its last accepted tokenself._graphs: Dict[Tuple[int, int], torch.cuda.CUDAGraph] = {}+ self._sampled_graphs: Dict[Tuple[int, int], torch.cuda.CUDAGraph] = {}def hidden_rows(self, rows: int) -> torch.Tensor:"""The input hidden-state buffer of ``rows`` (= batch size x verify width) rows, to write in place."""@@ -96,7 +97,9 @@ class DraftExtend:def run(self, bs: int, width: int) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:"""Run the staged round's extend, stage the next round and seed its tree; returns views``(topk_p, topk_index, hidden)`` of ``[bs, ...]`` (valid until the next call)."""- graph = self._graphs.get((bs, width))+ sampled = self.steps.sampled+ graphs = self._sampled_graphs if sampled is not None and sampled.active else self._graphs+ graph = graphs.get((bs, width))if graph is not None:graph.replay()else:@@ -108,6 +111,13 @@ class DraftExtend:"""Capture one draft-extend graph per batch size and verify width."""keys = [(bs, w) for bs in sorted(batch_sizes, reverse=True) for w in self._widths(bs) if w <= self.width]self._graphs = capture_graphs(keys, self._forward)+ sampled = self.steps.sampled+ if sampled is not None:+ sampled.active = True+ try:+ self._sampled_graphs = capture_graphs(keys, self._forward)+ finally:+ sampled.active = Falselogger.info("eagle-harness: captured %d draft-extend graphs", len(self._graphs))def _forward(self, key: Tuple[int, int]) -> None:@@ -127,7 +137,11 @@ class DraftExtend:hidden_states=self.input_hidden[:rows],)tree = self.tree- probs, tokens = draft_topk(self.model, normed.index_select(0, last), tree.shape.top_k)+ sampled = self.steps.sampled+ if sampled is not None and sampled.active:+ probs, tokens = sampled.draw(self.model, normed.index_select(0, last), bs, 0)+ else:+ probs, tokens = draft_topk(self.model, normed.index_select(0, last), tree.shape.top_k)tree.root_probs[:bs] = probstree.root_tokens[:bs] = tokenstorch.index_select(hidden, 0, last, out=tree.root_hidden[:bs])diff --git a/eagle_harness/sglang/draft_steps.py b/eagle_harness/sglang/draft_steps.pyindex de386f7..f969305 100644--- a/eagle_harness/sglang/draft_steps.py+++ b/eagle_harness/sglang/draft_steps.py@@ -17,7 +17,7 @@ from __future__ import annotationsimport loggingfrom dataclasses import dataclass-from typing import Callable, Dict, Sequence, Tuple, TypeVar+from typing import Callable, Dict, Optional, Sequence, Tuple, TypeVarimport torch@@ -97,7 +97,9 @@ def capture_graphs(keys: Sequence[K], body: Callable[[K], None]) -> Dict[K, torcclass DraftSteps:"""Owns the per-step graphs of the draft tree."""- def __init__(self, draft_runner, tree: DraftTree, attention: DraftRowAttention):+ def __init__(self, draft_runner, tree: DraftTree, attention: DraftRowAttention, *, sampled_seed: Optional[int] = None):+ """``sampled_seed``: the Philox seed of the recorded-q sampled tree (the same on every TP rank); None builds+ no sampled tree (the engine's verify cannot sample it)."""self.runner = draft_runnerself.model = draft_runner.modelself.tree = tree@@ -112,6 +114,14 @@ class DraftSteps:# Host mirror of tree.deltas, written by the graphs of the tree's delta slots (0: begin, d: step d).self.host_deltas = torch.zeros(tree.deltas.shape, dtype=torch.float32, pin_memory=True)self._graphs: Dict[Tuple[int, int], torch.cuda.CUDAGraph] = {}+ self.sampled = None+ if sampled_seed is not None and hasattr(self.model, "proposal_candidates"):+ from eagle_harness.sglang.sampled_tree import SampledTree++ self.sampled = SampledTree(+ tree, self.model.num_candidates, sampled_seed, req_index=self.req_pool_indices, rows=self.req_to_token.shape[0]+ )+ self._sampled_graphs: Dict[Tuple[int, int], torch.cuda.CUDAGraph] = {}@propertydef max_step(self) -> int:@@ -135,7 +145,8 @@ class DraftSteps:def run(self, bs: int, step: int) -> None:"""Replay draft step ``step`` (0: :meth:`DraftTree.begin`)."""- graph = self._graphs.get((bs, step))+ graphs = self._sampled_graphs if self.sampled is not None and self.sampled.active else self._graphs+ graph = graphs.get((bs, step))if graph is not None:graph.replay()else:@@ -145,6 +156,12 @@ class DraftSteps:"""Capture begin and every step for each batch size (largest first)."""keys = [(bs, step) for bs in sorted(batch_sizes, reverse=True) for step in range(self.max_step, -1, -1)]self._graphs = capture_graphs(keys, self._body)+ if self.sampled is not None:+ self.sampled.active = True+ try:+ self._sampled_graphs = capture_graphs(keys, self._body)+ finally:+ self.sampled.active = Falselogger.info("eagle-harness: captured %d draft-step graphs (bs %s)", len(self._graphs), sorted(batch_sizes))# ------------------------------------------------------------------ body@@ -173,5 +190,8 @@ class DraftSteps:out_cache_loc=slots,hidden_states=tree.front_hidden[:rows],)- probs, tokens = draft_topk(self.model, normed, k)+ if self.sampled is not None and self.sampled.active:+ probs, tokens = self.sampled.draw(self.model, normed, bs, step)+ else:+ probs, tokens = draft_topk(self.model, normed, k)tree.step(bs, step, probs, tokens, hidden)diff --git a/eagle_harness/sglang/drafter.py b/eagle_harness/sglang/drafter.pyindex cef8518..e04c285 100644--- a/eagle_harness/sglang/drafter.py+++ b/eagle_harness/sglang/drafter.py@@ -264,6 +264,7 @@ class DynamicDrafter:self._prelaunch_stream: Optional[torch.cuda.Stream] = Noneself.last_depth = 0self.last_width = 0+ self._sampled_depth = tree.shape.max_depth# ----------------------------------------------------------------- policydef bucket(self, bs: int) -> int:@@ -435,9 +436,14 @@ class DynamicDrafter:scores = ranking.scores[:verify_count]self._verify_scores.launch(scores)self._have_lagged = True- width = fit_width(- self._verify_width(policy, scores.tolist(), verify_count, bs, context, lagged=False), widths, nodes + 1- )+ sampled = getattr(self.steps, "sampled", None)+ if sampled is not None and sampled.active:+ # No history: use the allowed budget, never inspect this round's draws to decide whether to verify them.+ width = fit_width(verify_count, widths, nodes + 1)+ else:+ width = fit_width(+ self._verify_width(policy, scores.tolist(), verify_count, bs, context, lagged=False), widths, nodes + 1+ )self.last_depth, self.last_width = depth, widthif width == 1:return self._trivial(batch)@@ -499,7 +505,7 @@ class DynamicDrafter:verify_input.prepared_mrope_positions = (verify_input.positions.to(torch.int64).flatten().unsqueeze(0).repeat(3, 1))- harness_input = HarnessVerifyInput.from_eagle(verify_input)+ harness_input = HarnessVerifyInput.from_eagle(verify_input, proposal_nodes=selection.top_scores_index)if bs == 1 and self._kv_indices is not None:harness_input.prepared_attn_args = build_attn_args(self._req_to_token, req_pool_indices, seq_lens, width, self._kv_indices@@ -533,7 +539,10 @@ class DynamicDrafter:def run() -> int:depth = 0- while depth < self.steps.max_step:+ limit = self.steps.max_step+ if getattr(self.steps, "sampled", None) is not None and self.steps.sampled.active:+ limit = self._sampled_depth - 1+ while depth < limit:kind = policy.width_step(depth)if kind is WidthStep.LAUNCH:self._launch_deltas(depth)@@ -548,6 +557,19 @@ class DynamicDrafter:def _grow(self, bs: int, depth: int, row: Optional[DraftCostRow], past: int, policy) -> int:"""Decide at ``depth`` (its step already queued), then step and decide until the policystops; returns the tree's depth levels."""+ if getattr(self.steps, "sampled", None) is not None and self.steps.sampled.active:+ planned = self._sampled_depth+ next_depth = None+ while True:+ stop = self._decide(depth, bs, row, past, policy)+ if stop and next_depth is None:+ next_depth = depth + 1+ if depth >= planned - 1:+ break+ depth += 1+ self.steps.run(bs, depth)+ self._sampled_depth = next_depth or min(planned + 2, self.tree.shape.max_depth)+ return plannedwhile not self._decide(depth, bs, row, past, policy):if depth == self.steps.max_step:return self.tree.shape.max_depthdiff --git a/eagle_harness/sglang/hooks.py b/eagle_harness/sglang/hooks.pyindex 7c1bb38..744cc2f 100644--- a/eagle_harness/sglang/hooks.py+++ b/eagle_harness/sglang/hooks.py@@ -147,6 +147,8 @@ HOOKS: tuple[Hook, ...] = (_RUN_VERIFY,CALL,),+ # T=1 recorded-q tree verification (worker.py); without it, temperature-1 rounds keep target-only verification.+ Hook("sglang.srt.speculative.eagle_worker_common:run_eagle_verify", ("sampling_step",), CALL, optional=True),Hook("sglang.srt.speculative.eagle_worker_common:VerifyAcceptInput", _ACCEPT_INPUT, CALL),Hook("sglang.srt.speculative.eagle_worker_common:VerifyAcceptResult", _ACCEPT_RESULT, CALL),# The EAGLE V2 worker the cost-model worker extends (prefill, pools, backends stay sglang's).@@ -223,7 +225,7 @@ def _problem(hook: Hook) -> str | None:return None if hook.optional else f"{hook.path} is missing"if hook.kind == OVERRIDE and found != hook.params:return f"{hook.path}{found} is not {hook.params}"- if hook.kind == CALL and not set(hook.params) <= set(found):+ if hook.kind == CALL and not set(hook.params) <= set(found) and not hook.optional:return f"{hook.path}{found} lacks {tuple(p for p in hook.params if p not in found)}"return Nonediff --git a/eagle_harness/sglang/models/llama_eagle4.py b/eagle_harness/sglang/models/llama_eagle4.pyindex 8655cbf..db85338 100644--- a/eagle_harness/sglang/models/llama_eagle4.py+++ b/eagle_harness/sglang/models/llama_eagle4.py@@ -62,7 +62,7 @@ from eagle_harness.models.eagle4_structure import ()from eagle_harness.models.low_rank_head import low_rank_scoresfrom eagle_harness.models.low_rank_head import low_rank_factors-from eagle_harness.kernels.candidate_ops import candidate_topk+from eagle_harness.kernels.candidate_ops import candidate_headfrom eagle_harness.sglang.algorithm import harness_configfrom eagle_harness.sglang.candidate_logits import (Candidates,@@ -364,6 +364,15 @@ class LlamaForCausalLMEagle4(LlamaForCausalLM):gather = tensor_model_parallel_all_gather if self._tp_size > 1 else Nonereturn merge_candidates(local, self.num_candidates, gather)+ def proposal_candidates(self, hidden: torch.Tensor) -> Candidates:+ """The complete sparse distribution the sampled draft draws from (``[rows, C]`` fp32 logits, int64 ids); on+ CUDA the greedy path's candidate pipeline without its top-k, so a sampled step costs the greedy step's+ collectives."""+ if not hidden.is_cuda:+ return self._candidates(hidden)+ logits, tokens, _ = self._candidate_head(hidden, 0)+ return Candidates(logits, tokens)+def candidate_topk(self, hidden: torch.Tensor, k: int) -> Tuple[torch.Tensor, torch.Tensor]:"""Top-``k`` next tokens of each row: ``([rows, k]`` fp32 probabilities, ``[rows, k]`` ids).@@ -371,13 +380,13 @@ class LlamaForCausalLMEagle4(LlamaForCausalLM):full-vocab softmax of :class:`CandidateLogitsProcessor`'s rows."""if hidden.is_cuda:- return self._fused_candidate_topk(hidden, k)+ return self._candidate_head(hidden, k)[2]candidates = self._candidates(hidden)probs, pick = torch.topk(torch.softmax(candidates.logits, dim=-1), k, dim=-1)return probs, torch.gather(candidates.token_ids, 1, pick)- def _fused_candidate_topk(self, hidden: torch.Tensor, k: int) -> Tuple[torch.Tensor, torch.Tensor]:- """:meth:`candidate_topk` on the candidate kernels (``candidate_ops.candidate_topk``), bit-identical to torch."""+ def _candidate_head(self, hidden: torch.Tensor, k: int):+ """``candidate_ops.candidate_head`` on this head's shard (bit-identical to torch): logits, ids, top-``k``."""shard = self.lm_head.shard_indicesscores = low_rank_scores(hidden,@@ -385,7 +394,7 @@ class LlamaForCausalLMEagle4(LlamaForCausalLM):self.efficient_lm_head.weight,shard.org_vocab_end_index - shard.org_vocab_start_index,)- return candidate_topk(+ return candidate_head(scores,self.lm_head.weight,hidden,diff --git a/eagle_harness/sglang/sampled_tree.py b/eagle_harness/sglang/sampled_tree.pynew file mode 100644index 0000000..903e8a2--- /dev/null+++ b/eagle_harness/sglang/sampled_tree.py@@ -0,0 +1,90 @@+# Copyright 2026 Eagle AI Corp.+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available+"""Recorded proposals indexed by the existing draft tree's expansion slots."""++import torch++from eagle_harness.kernels.sampled_draw import sample_children+++class SampledTree:+ """Static proposal storage; node ids remain the ordinary DraftTree ids.++ Expansion slot 0 is the root, then K frontier rows per draft step. Scores+ are q's order statistics assigned in draw order, so pruning preserves+ sibling prefixes without conditioning on the proposed token itself.++ Draws come from counter-based Philox keyed by the TP-synchronized seed, a+ device round counter advanced by the root draw's graph and the draft step,+ so every TP rank draws the same tree with no collective (the EAGLE-4 fork's+ scheme). One Triton launch per draft step records q and draws the children.+ """++ def __init__(self, tree, candidates: int, seed: int = 0, *, req_index=None, rows: int = 0):+ self.tree = tree+ shape = tree.shape+ device = tree.tokens.device+ slots = 1 + (shape.max_depth - 1) * shape.top_k+ # Stores are indexed by the request's pool slot (``req_index`` = the drafter's staged req_pool_indices), so a+ # recorded root proposal follows its request across batch changes; without a map, by batch position.+ rows = max(rows, tree.max_bs)+ self.req_index = req_index if req_index is not None else torch.arange(tree.max_bs, dtype=torch.int64, device=device)+ self.q = torch.zeros((rows, slots, candidates), device=device)+ self.ids = torch.zeros_like(self.q, dtype=torch.int64)+ self.positions = torch.zeros((rows, tree.tokens.shape[1]), dtype=tree.tokens.dtype, device=device)+ self.root_valid = torch.zeros(rows, dtype=torch.bool, device=device)+ self.seed = int(seed)+ self.round = torch.zeros(1, dtype=torch.int32, device=device)+ self.active = False++ def draw(self, model, hidden, bs, step):+ """Record the exact candidate distribution and draw the children, in place, in one launch."""+ candidates = model.proposal_candidates(hidden)+ k = self.tree.shape.top_k+ rows = 1 if step == 0 else k+ slot = 0 if step == 0 else 1 + (step - 1) * k+ if step == 0:+ self.round += 1 # a round's draws start with the root; replayed identically on every rank+ self.root_valid.index_fill_(0, self.req_index[:bs], True)+ return sample_children(+ candidates.logits,+ candidates.token_ids,+ k,+ seed=self.seed,+ launch=step,+ counter=self.round,+ q=self.q,+ q_ids=self.ids,+ positions=self.positions,+ slot=slot,+ start=self.tree.shape.layer_start(step + 1),+ rows_per_req=rows,+ req_index=self.req_index[:bs],+ )++ def invalidate(self, req_pool_indices: torch.Tensor) -> None:+ """Requests whose root tokens come from a prefill (no recorded q): their first round emits one target token."""+ self.root_valid.index_fill_(0, req_pool_indices.to(device=self.root_valid.device, dtype=torch.int64), False)++ def sample(self, verify_input, target_probs, uniforms, final_uniforms):+ """Probability-only host seam, after target temperature and filtering."""+ from eagle_harness.kernels.sampled_tree import sample_tree++ bs = target_probs.shape[0]+ return sample_tree(+ target_probs,+ self.q,+ self.ids,+ self.positions,+ self.root_valid,+ verify_input.proposal_nodes,+ verify_input.draft_token,+ verify_input.retrieve_index,+ verify_input.retrieve_next_token,+ verify_input.retrieve_next_sibling,+ uniforms,+ final_uniforms,+ top_k=self.tree.shape.top_k,+ max_depth=verify_input.max_tree_depth,+ req_index=self.req_index[:bs],+ )diff --git a/eagle_harness/sglang/verify_input.py b/eagle_harness/sglang/verify_input.pyindex 982edd5..df94cd8 100644--- a/eagle_harness/sglang/verify_input.py+++ b/eagle_harness/sglang/verify_input.py@@ -69,6 +69,8 @@ class HarnessVerifyInput(EagleVerifyInput):# A greedy round: the target returns the rows' argmax, not their logits.greedy_tokens_only: bool = False+ # Raw draft node ids of the selected non-root rows, in verify-row order.+ proposal_nodes: Optional[torch.Tensor] = dataclasses.field(default=None, repr=False)# The tail-mask attention of the batch-size-1 verify graphs (set on the inputs they are captured with).tail_mask: Optional["TreeTailMask"] = dataclasses.field(default=None, repr=False)# (kv_indices, kv_indptr, qo_indptr) of a one-request verify over untranslated KV ids, built with the restdiff --git a/eagle_harness/sglang/worker.py b/eagle_harness/sglang/worker.pyindex 6f8c60b..967cc1c 100644--- a/eagle_harness/sglang/worker.py+++ b/eagle_harness/sglang/worker.py@@ -36,6 +36,7 @@ next draft on a side stream before waiting for verify.from __future__ import annotationsimport contextlib+from functools import partialimport loggingimport osfrom typing import TYPE_CHECKING, Optional, Union@@ -71,6 +72,7 @@ from eagle_harness.sglang.plain_decode import NativeDecodefrom eagle_harness.sglang.row_attention import DraftRowAttentionfrom eagle_harness.sglang.verify_step import AcceptTailGraphs, fused_accept_step, fused_accept_supportedfrom eagle_harness.sglang.verify_graphs import verify_widths+from eagle_harness.sglang.hooks import parameter_namesfrom eagle_harness.sglang.verify_input import HarnessVerifyInputif TYPE_CHECKING:@@ -96,6 +98,12 @@ def cost_key(runner) -> CostKey:)+def _sampled_tree(worker):+ """The draft's recorded-q sampled tree, or None: engines without sglang's verify sampler hook build none, and a+ worker built without sglang's __init__ (or serving natively, OFF) may have no draft steps to ask."""+ return getattr(getattr(getattr(worker, "_draft_worker", None), "steps", None), "sampled", None)++class HarnessDraftWorker(EagleDraftWorker):"""sglang's EAGLE draft worker with the harness's decode-time draft forwards.@@ -141,7 +149,10 @@ class HarnessDraftWorker(EagleDraftWorker):self.draft_runner, max_bs=max_bs, max_rows_per_request=max(self.topk, width), window=getattr(model, "window", model.get_attention_sliding_window_size()))self.draft_runner.draft_attn_backend = self.draft_attn_backend- self.steps = DraftSteps(self.draft_runner, self.tree, self.draft_attn_backend)+ # The sampled tree needs sglang's verify tree-sampler hook; engines without it keep 0.1.0's T=1 path (greedy+ # draft, target-only verify). Its draws are keyed by sglang's TP-synchronized seed: every rank draws alike.+ sampled_seed = self.target_worker.random_seed if "sampling_step" in parameter_names(run_eagle_verify) else None+ self.steps = DraftSteps(self.draft_runner, self.tree, self.draft_attn_backend, sampled_seed=sampled_seed)intensity = self._intensityself.extend = DraftExtend(self.draft_runner,@@ -336,6 +347,10 @@ class EagleHarnessWorker(EAGLEWorkerV2):if batch.forward_mode.is_extend() or batch.is_extend_in_batch:self._drafter.cancel_prelaunch()rounds.interrupt()+ sampled = _sampled_tree(self)+ if sampled is not None:+ # Prefilled requests start from sglang's deterministic top-k roots: no recorded proposal distribution.+ sampled.invalidate(batch.req_pool_indices)return super().forward_batch_generation(batch, on_publish, grammar_barrier, pp_proxy_tensors)native_decode = self._native_decode.select(batch)if native_decode:@@ -343,6 +358,23 @@ class EagleHarnessWorker(EAGLEWorkerV2):result = self._native_decode.run(batch, grammar_barrier)self._verified.record()else:+ sampled = _sampled_tree(self)+ if sampled is not None:+ active = (+ self.topk > 1+ and not batch.forward_mode.is_idle()+ and not batch.sampling_info.is_all_greedy+ and all(req.sampling_params.temperature == 1.0 for req in batch.reqs)+ and not batch.has_grammar+ and batch.sampling_info.acc_additive_penalties is None+ and batch.sampling_info.acc_scaling_penalties is None+ and not batch.sampling_info.has_watermark_candidates+ )+ if active != sampled.active:+ self._drafter.cancel_prelaunch()+ sampled.root_valid.zero_() # this round's roots were drafted without recorded proposals+ logger.debug("eagle-harness: sampled tree %s", "on" if active else "off")+ sampled.active = activedraft = self._draft_workertimer = self._drafter.timerif batch.forward_mode.is_idle():@@ -410,6 +442,10 @@ class EagleHarnessWorker(EAGLEWorkerV2):staged=(steps.seq_lens[:1], steps.req_pool_indices[:1]),extend=self._draft_worker.extend,)+ sampled = _sampled_tree(self)+ hook = {} # never passed to an engine without the hook (sampled is None there)+ if sampled is not None and sampled.active and width > 1:+ hook["sampling_step"] = partial(sampled.sample, batch.spec_info)result = run_eagle_verify(batch,target_worker=self.target_worker,@@ -424,6 +460,7 @@ class EagleHarnessWorker(EAGLEWorkerV2):finalize_tree_path=True,grammar_barrier=grammar_barrier,accept_step=accept_step,+ **hook,)if accept_step is not None and batch.enable_overlap:# The scheduler reads on a leaf stream; the next tail replay may overwrite its graph buffers.diff --git a/tests/test_draft_extend.py b/tests/test_draft_extend.pyindex b0adb2d..6717fac 100644--- a/tests/test_draft_extend.py+++ b/tests/test_draft_extend.py@@ -31,6 +31,7 @@ def _extend():began = []steps = SimpleNamespace(tree=tree,+ sampled=None,seq_lens=torch.zeros(MAX_BS, dtype=torch.long),req_pool_indices=torch.zeros(MAX_BS, dtype=torch.long),begin_body=began.append,diff --git a/tests/test_drafter.py b/tests/test_drafter.pyindex 2aede05..02df392 100644--- a/tests/test_drafter.py+++ b/tests/test_drafter.py@@ -133,6 +133,18 @@ def test_prelaunched_and_direct_rounds_run_the_same_steps(stop):assert steps.ran == resumed_steps.ran == list(range(1, stop + 1))[email protected]("stop", [3, 5, 99])+def test_sampled_depth_uses_the_previous_round_plan(stop):+ drafter, steps = _sequenced(True, stop)+ steps.sampled = SimpleNamespace(active=True)+ drafter._sampled_depth = 6+ first = drafter._queue_until_decision(1, drafter.cost)+ depth = drafter._grow(1, first, None, 32, drafter.cost)+ assert depth == 6+ assert steps.ran == list(range(1, 6))+ assert drafter._sampled_depth == (stop + 1 if stop <= 5 else 8)++def test_grow_stops_at_the_deepest_level():drafter, steps = _sequenced(True, stop=99)assert drafter._grow(1, drafter._queue_until_decision(1, drafter.cost), None, 32, drafter.cost) == DEPTHdiff --git a/tests/test_sampled_draw_gpu.py b/tests/test_sampled_draw_gpu.pynew file mode 100644index 0000000..07bc70c--- /dev/null+++ b/tests/test_sampled_draw_gpu.py@@ -0,0 +1,124 @@+# Copyright 2026 Eagle AI Corp.+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available++"""The one-launch recorded-q draw equals the torch reference draw and its Philox stream is TP-rank independent."""++import os++import pytest+import torch++from eagle_harness.core.sampled_tree import draw_children++pytest.importorskip("triton")+from tests.triton_probe import needs_triton # noqa: E402++INTERPRET = os.environ.get("TRITON_INTERPRET") == "1"+DEV = "cpu" if INTERPRET else "cuda"+pytestmark = needs_triton+++def _stores(bs, slots, nc, nodes):+ q = torch.zeros((bs, slots, nc), device=DEV)+ ids = torch.zeros((bs, slots, nc), dtype=torch.int64, device=DEV)+ positions = torch.zeros((bs, nodes), dtype=torch.int64, device=DEV)+ return q, ids, positions++[email protected]("k, rows_per_req, step", [(4, 1, 0), (4, 4, 2), (2, 2, 1), (1, 1, 0)])+def test_fused_draw_matches_reference_on_shared_uniforms(k, rows_per_req, step):+ from eagle_harness.kernels.sampled_draw import sample_children++ bs, nc = 3, 128+ gen = torch.Generator().manual_seed(11 + k + step)+ rows = bs * rows_per_req+ logits = (torch.randn(rows, nc, generator=gen) * 2).to(DEV)+ token_ids = torch.stack([torch.randperm(5000, generator=gen)[:nc] for _ in range(rows)]).to(DEV)+ uniforms = torch.rand(rows, nc, generator=gen).to(DEV)+ reference = draw_children(logits, token_ids, k, uniforms=uniforms)+ slots, nodes = 1 + 3 * k, 1 + 4 * k * k+ slot = 0 if step == 0 else 1 + (step - 1) * k+ start = 1 + step * k * rows_per_req # any layout offset: the kernel writes where it is told+ q, ids, positions = _stores(bs, slots, nc, nodes)+ scores, tokens = sample_children(+ logits, token_ids, k, seed=1, launch=step, counter=torch.ones(1, dtype=torch.int32, device=DEV),+ q=q, q_ids=ids, positions=positions, slot=slot, start=start, rows_per_req=rows_per_req, uniforms=uniforms,+ )+ if not INTERPRET:+ torch.cuda.synchronize()+ torch.testing.assert_close(tokens, reference.tokens, rtol=0, atol=0)+ torch.testing.assert_close(positions[:, start : start + rows_per_req * k].reshape(rows, k), reference.positions, rtol=0, atol=0)+ torch.testing.assert_close(scores, reference.scores, rtol=1e-6, atol=1e-7)+ torch.testing.assert_close(q[:, slot : slot + rows_per_req].reshape(rows, nc), reference.probs, rtol=1e-6, atol=1e-7)+ torch.testing.assert_close(ids[:, slot : slot + rows_per_req].reshape(rows, nc), reference.token_ids, rtol=0, atol=0)+ # nothing written outside the addressed slots / children+ untouched = torch.ones(slots, dtype=torch.bool)+ untouched[slot : slot + rows_per_req] = False+ assert q[:, untouched].abs().sum() == 0 and ids[:, untouched].abs().sum() == 0+ mask = torch.ones(nodes, dtype=torch.bool)+ mask[start : start + rows_per_req * k] = False+ assert positions[:, mask].abs().sum() == 0+++def test_philox_draws_are_deterministic_per_round_and_launch_and_fresh_across_rounds():+ from eagle_harness.kernels.sampled_draw import sample_children++ nc, k = 64, 4+ gen = torch.Generator().manual_seed(5)+ logits = torch.randn(2, nc, generator=gen).to(DEV)+ token_ids = torch.arange(nc).expand(2, -1).contiguous().to(DEV)++ def draw(seed, rnd, launch):+ q, ids, positions = _stores(2, 1, nc, k)+ counter = torch.full((1,), rnd, dtype=torch.int32, device=DEV)+ _, tokens = sample_children(logits, token_ids, k, seed=seed, launch=launch, counter=counter, q=q, q_ids=ids,+ positions=positions, slot=0, start=0, rows_per_req=1)+ if not INTERPRET:+ torch.cuda.synchronize()+ return tokens.cpu()++ a, b = draw(721, 3, 1), draw(721, 3, 1) # two ranks: same seed, same round, same launch -> same tree+ torch.testing.assert_close(a, b, rtol=0, atol=0)+ others = [draw(721, 4, 1), draw(721, 3, 2), draw(722, 3, 1)]+ assert any(not torch.equal(a, o) for o in others)+ assert sum(not torch.equal(a, o) for o in others) >= 2+++def test_philox_first_child_follows_q():+ """The first Gumbel-top-K draw is a sample from q: chi-square over many rows of one distribution."""+ from eagle_harness.kernels.sampled_draw import sample_children++ nc, k, rows = 8, 2, (2048 if INTERPRET else 65536)+ q_true = torch.tensor([0.4, 0.25, 0.15, 0.1, 0.05, 0.03, 0.015, 0.005])+ logits = q_true.log().expand(rows, -1).contiguous().to(DEV)+ token_ids = torch.arange(nc).expand(rows, -1).contiguous().to(DEV)+ q, ids, positions = _stores(rows, 1, nc, k)+ _, tokens = sample_children(logits, token_ids, k, seed=9, launch=0, counter=torch.ones(1, dtype=torch.int32, device=DEV),+ q=q, q_ids=ids, positions=positions, slot=0, start=0, rows_per_req=1)+ if not INTERPRET:+ torch.cuda.synchronize()+ counts = torch.bincount(tokens[:, 0].cpu(), minlength=nc).double()+ expected = q_true.double() * rows+ chi2 = ((counts - expected) ** 2 / expected).sum().item()+ assert chi2 < 30.0, chi2 # 7 dof: 30 is far beyond the 99.99% point (24.3)+ assert (tokens[:, 0] != tokens[:, 1]).all() # without replacement+++def test_stores_follow_the_request_slot_map():+ from eagle_harness.kernels.sampled_draw import sample_children++ nc, k = 32, 2+ gen = torch.Generator().manual_seed(3)+ logits = torch.randn(2, nc, generator=gen).to(DEV)+ token_ids = torch.arange(nc).expand(2, -1).contiguous().to(DEV)+ uniforms = torch.rand(2, nc, generator=gen).to(DEV)+ reference = draw_children(logits, token_ids, k, uniforms=uniforms)+ q, ids, positions = _stores(8, 3, nc, 5)+ req = torch.tensor([5, 2], device=DEV)+ sample_children(logits, token_ids, k, seed=1, launch=1, counter=torch.ones(1, dtype=torch.int32, device=DEV),+ q=q, q_ids=ids, positions=positions, slot=1, start=3, rows_per_req=1, uniforms=uniforms, req_index=req)+ if not INTERPRET:+ torch.cuda.synchronize()+ torch.testing.assert_close(q[req, 1], reference.probs, rtol=1e-6, atol=1e-7)+ torch.testing.assert_close(positions[req, 3:5], reference.positions, rtol=0, atol=0)+ assert q[[0, 1, 3, 4, 6, 7]].abs().sum() == 0 and q[:, [0, 2]].abs().sum() == 0diff --git a/tests/test_sampled_tree.py b/tests/test_sampled_tree.pynew file mode 100644index 0000000..28a994d--- /dev/null+++ b/tests/test_sampled_tree.py@@ -0,0 +1,207 @@+# Copyright 2026 Eagle AI Corp.+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available++"""Distribution and layout contracts of without-replacement tree proposals."""++import pytest+import torch+++def chi_square_statistic(samples, probabilities):+ counts = torch.bincount(samples.cpu(), minlength=len(probabilities)).double()+ expected = probabilities.double().cpu() * samples.numel()+ mask = expected > 0+ statistic = ((counts[mask] - expected[mask]).square() / expected[mask]).sum().item()+ return statistic, counts[~mask].sum().item()+++def chi_square(samples, probabilities):+ statistic, outside = chi_square_statistic(samples, probabilities)+ assert outside == 0+ # df <= 7; 40 is beyond the 1e-6 upper tail (fixed seeds, no retries).+ assert statistic < 40, statistic+ return statistic+++ "device", ["cpu", pytest.param("cuda", marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA"))]+)+def test_draws_record_the_actual_distribution_and_order(device):+ from eagle_harness.core.sampled_tree import draw_children++ gen = torch.Generator(device=device).manual_seed(182)+ q = torch.tensor([0.6, 0.25, 0.1, 0.05], device=device)+ ids = torch.tensor([4, 0, 6, 2], device=device)+ n = 40000+ draw = draw_children(q.log().expand(n, -1), ids.expand(n, -1), 3, generator=gen)+ torch.testing.assert_close(draw.probs, q.expand(n, -1))+ torch.testing.assert_close(draw.token_ids, ids.expand(n, -1))+ torch.testing.assert_close(draw.tokens, draw.token_ids.gather(1, draw.positions))+ assert (draw.positions.sort(dim=1).values.diff(dim=1) > 0).all()+ chi_square(draw.positions[:, 0], q)+ second = torch.stack([sum(q[i] * q[j] / (1 - q[i]) for i in range(4) if i != j) for j in range(4)])+ chi_square(draw.positions[:, 1], second)+ # Policy scores must not reveal the sampled token (sorting samples biases q).+ torch.testing.assert_close(draw.scores, q[:3].expand(n, -1))++[email protected]("width", [1, 2, 3, 4])[email protected]("seed", [28, 182, 917])+def test_recursive_rejection_emits_target_including_outside_proposals(width, seed):+ from eagle_harness.core.sampled_tree import draw_children, reject_children++ n = 30000+ gen = torch.Generator().manual_seed(seed)+ q = torch.tensor([0.7, 0.2, 0.08, 0.02])+ ids = torch.tensor([4, 1, 0, 5])+ p = torch.tensor([0.1, 0.0, 0.2, 0.35, 0.25, 0.1])+ draw = draw_children(q.log().expand(n, -1), ids.expand(n, -1), width, generator=gen)+ result = reject_children(p.expand(n, -1), draw, torch.rand(n, width, generator=gen), torch.rand(n, generator=gen))+ chi_square(result.tokens, p)+ assert (result.accepted_position >= -1).all()+ accepted = result.accepted_position >= 0+ assert accepted.any()+ assert torch.equal(+ result.tokens[accepted], draw.tokens[accepted].gather(1, result.accepted_position[accepted, None]).flatten()+ )+++def test_a_verifier_that_subtracts_only_the_rejected_token_fails_the_distribution_check():+ """The gate has power: the classic mistake of removing only the rejected token's q mass from the residual+ (instead of the whole conditional q) biases the output, and the same check that passes the real recursion+ rejects it."""+ from eagle_harness.core.sampled_tree import draw_children++ n, width = 30000, 2+ gen = torch.Generator().manual_seed(28)+ q = torch.tensor([0.7, 0.2, 0.08, 0.02])+ ids = torch.tensor([4, 1, 0, 5])+ p = torch.tensor([0.1, 0.0, 0.2, 0.35, 0.25, 0.1])+ draw = draw_children(q.log().expand(n, -1), ids.expand(n, -1), width, generator=gen)+ coins, final = torch.rand(n, width, generator=gen), torch.rand(n, generator=gen)+ residual, remaining = p.double().expand(n, -1).clone(), draw.probs.double().clone()+ chosen = torch.full((n,), -1)+ for child in range(width):+ token = draw.tokens[:, child : child + 1]+ mass = residual.sum(dim=-1)+ q_y = (remaining / remaining.sum(dim=-1, keepdim=True)).gather(1, draw.positions[:, child : child + 1]).flatten()+ p_y = residual.gather(1, token).flatten()+ accept = (chosen == -1) & (coins[:, child] * mass * q_y < p_y)+ chosen = torch.where(accept, child, chosen)+ biased = residual.scatter(1, token, (p_y - mass * q_y).clamp_min(0)[:, None]) # the mutation+ residual = torch.where((chosen == -1)[:, None], biased, residual)+ remaining.scatter_(1, draw.positions[:, child : child + 1], 0)+ cdf = residual.cumsum(dim=-1)+ bonus = torch.searchsorted(cdf, (final.double() * cdf[:, -1])[:, None], right=True).flatten()+ tokens = torch.where(chosen == -1, bonus, draw.tokens.gather(1, chosen.clamp_min(0)[:, None]).flatten())+ statistic, outside = chi_square_statistic(tokens, p)+ assert statistic >= 40 or outside > 0, statistic+++def test_equal_proposal_always_accepts_first_draw():+ from eagle_harness.core.sampled_tree import draw_children, reject_children++ gen = torch.Generator().manual_seed(9)+ p = torch.tensor([[0.6, 0.3, 0.1]]).expand(10000, -1)+ ids = torch.arange(3).expand(10000, -1)+ draw = draw_children(p.log(), ids, 3, generator=gen)+ out = reject_children(p, draw, torch.rand(10000, 3, generator=gen), torch.rand(10000, generator=gen))+ assert (out.accepted_position == 0).all()+ assert torch.equal(out.tokens, draw.tokens[:, 0])+++def test_one_hot_and_exhausted_support_never_emit_padding():+ from eagle_harness.core.sampled_tree import draw_children, reject_children++ gen = torch.Generator().manual_seed(3)+ q = torch.tensor([[1.0, 0.0, 0.0]]).expand(1000, -1)+ ids = torch.tensor([[2, 0, 1]]).expand(1000, -1)+ draw = draw_children(q.log(), ids, 3, generator=gen)+ assert (draw.tokens[:, 0] == 2).all()+ assert (draw.scores[:, 1:] == 0).all()+ p = torch.tensor([[0.25, 0.75, 0.0]]).expand(1000, -1)+ out = reject_children(p, draw, torch.zeros(1000, 3), torch.rand(1000, generator=gen))+ assert (out.accepted_position == -1).all()+ chi_square(out.tokens, p[0])++[email protected]("tied", [False, True])+def test_tree_pruning_preserves_proposal_prefixes_and_raw_node_mapping(tied):+ from eagle_harness.core.draft_tree import DraftTree, TreeShape+ from eagle_harness.core.sampled_tree import draw_children++ bs, k, depth, candidates = 4, 4, 4, 6+ generator = torch.Generator().manual_seed(932)+ shape = TreeShape(k, depth)+ tree = DraftTree(shape, bs, 2, torch.float32, torch.device("cpu"), max_verify=16)+ proposal_ids, proposal_positions = [], []+ for step in range(depth):+ rows = bs if step == 0 else bs * k+ logits = torch.randn(rows, candidates, generator=generator)+ if tied:+ logits.zero_()+ ids = torch.stack([torch.randperm(11, generator=generator)[:candidates] for _ in range(rows)])+ draw = draw_children(logits, ids, k, generator=generator)+ proposal_ids.append(ids.view(bs, -1, candidates))+ proposal_positions.append(draw.positions.view(bs, -1))+ hidden = torch.zeros(rows, 2)+ if step == 0:+ tree.stage_root(bs, draw.scores, draw.tokens, hidden)+ tree.begin(bs)+ else:+ tree.set_step_slots(bs, step, torch.zeros(bs, k, dtype=torch.long))+ tree.step(bs, step, draw.scores, draw.tokens, hidden)+ ranked, _ = tree.rank(bs, step + 1, 15)+ for width in range(1, min(16, shape.num_nodes(step + 1) + 1) + 1):+ selected = tree.select(bs, step + 1, ranked, width)+ q_ids = torch.cat(proposal_ids, dim=1)+ positions = torch.cat(proposal_positions, dim=1)+ for row, raw_nodes in enumerate(selected.top_scores_index.tolist()):+ retained = set(raw_nodes)+ for col, node in enumerate(raw_nodes):+ slot, order = node // k, node % k+ assert all(slot * k + earlier in retained for earlier in range(order))+ if node >= k:+ assert int(selected.parent_list[row, slot]) in retained+ assert selected.draft_tokens[row, col] == q_ids[row, slot, positions[row, node]]++[email protected]("width", [2, 3, 4, 5, 6])+def test_token_dependent_descendants_do_not_bias_pruned_root_distribution(width):+ from eagle_harness.core.draft_tree import DraftTree, TreeShape+ from eagle_harness.core.sampled_tree import ChildProposals, draw_children, reject_children++ n, k = 30000, 2+ generator = torch.Generator().manual_seed(496)+ p = torch.tensor([0.1, 0.2, 0.3, 0.4])+ q = torch.tensor([0.6, 0.25, 0.1, 0.05])+ draw = draw_children(q.log().expand(n, -1), torch.arange(4).expand(n, -1), k, generator=generator)+ tree = DraftTree(TreeShape(k, 2), n, 1, torch.float32, torch.device("cpu"), max_verify=6)+ tree.stage_root(n, draw.scores, draw.tokens, torch.zeros(n, 1))+ tree.begin(n)+ # A sampled parent's identity controls how many descendants outrank its siblings.+ conditional = torch.tensor(+ [[0.97, 0.01, 0.01, 0.01], [0.25, 0.25, 0.25, 0.25], [0.6, 0.3, 0.05, 0.05], [0.4, 0.3, 0.2, 0.1]]+ )+ child = draw_children(+ conditional[tree.front_tokens].log(), torch.arange(4).expand(n * k, -1), k, generator=generator+ )+ tree.set_step_slots(n, 1, torch.zeros(n, k, dtype=torch.long))+ tree.step(n, 1, child.scores, child.tokens, torch.zeros(n * k, 1))+ ranked, _ = tree.rank(n, 2, 5)+ selected = tree.select(n, 2, ranked, width)+ retained = (selected.top_scores_index < k).sum(dim=1)+ coins, final = torch.rand(n, k, generator=generator), torch.rand(n, generator=generator)+ output = torch.empty(n, dtype=torch.long)+ for count in range(1, k + 1):+ mask = retained == count+ proposal = ChildProposals(+ draw.probs[mask],+ draw.token_ids[mask],+ draw.positions[mask, :count],+ draw.tokens[mask, :count],+ draw.scores[mask, :count],+ )+ output[mask] = reject_children(p.expand(int(mask.sum()), -1), proposal, coins[mask, :count], final[mask]).tokens+ assert (retained >= 1).all()+ chi_square(output, p)diff --git a/tests/test_sampled_tree_gpu.py b/tests/test_sampled_tree_gpu.pynew file mode 100644index 0000000..8189004--- /dev/null+++ b/tests/test_sampled_tree_gpu.py@@ -0,0 +1,229 @@+# Copyright 2026 Eagle AI Corp.+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available++"""GPU parity of recorded-q verification with the CPU probability recursion."""++import os++import pytest+import torch++from eagle_harness.core.sampled_tree import draw_children, reject_children++pytest.importorskip("triton")+from tests.triton_probe import needs_triton # noqa: E402++INTERPRET = os.environ.get("TRITON_INTERPRET") == "1"+pytestmark = needs_triton++[email protected]("k", [1, 2, 4])[email protected]("root_valid", [True, False])[email protected]("layout_dtype", [torch.int32, torch.int64])+def test_gpu_recursive_rejection_matches_reference(k, root_valid, layout_dtype):+ from eagle_harness.kernels.sampled_tree import sample_tree++ n, width = (32 if INTERPRET else 30000), k + 1+ gen = torch.Generator().manual_seed(295)+ p = torch.tensor([0.1, 0.0, 0.2, 0.35, 0.25, 0.1])+ q = torch.tensor([0.7, 0.2, 0.08, 0.02])+ ids = torch.tensor([4, 1, 0, 5])+ draw = draw_children(q.log().expand(n, -1), ids.expand(n, -1), k, generator=gen)+ coins = torch.rand(n, width, generator=gen)+ final = torch.rand(n, generator=gen)+ reference = reject_children(p.expand(n, -1), draw, coins[:, 1:], final)+ target = p.expand(n, width, -1).contiguous()+ next_child = torch.full((n, width), -1, dtype=layout_dtype)+ next_child[:, 0] = 1+ siblings = torch.full_like(next_child, -1)+ siblings[:, 1:-1] = torch.arange(2, width, dtype=layout_dtype)+ tokens = torch.cat((torch.zeros(n, 1, dtype=torch.int64), draw.tokens), dim=1)+ args = [+ target,+ draw.probs[:, None, :].contiguous(),+ draw.token_ids[:, None, :].contiguous(),+ draw.positions,+ torch.full((n,), root_valid),+ torch.arange(k).expand(n, -1).contiguous(),+ tokens,+ torch.arange(n * width).view(n, width).to(layout_dtype),+ next_child,+ siblings,+ coins,+ final,+ ]+ gpu_args = [a.to("cpu" if INTERPRET else "cuda") for a in args]+ predict, lengths, path = sample_tree(*gpu_args, top_k=k, max_depth=2)+ if not INTERPRET:+ torch.cuda.synchronize()+ actual = predict.cpu().view(n, width)[:, 0]+ if root_valid:+ torch.testing.assert_close(actual.long(), reference.tokens, rtol=0, atol=0)+ torch.testing.assert_close(lengths.cpu(), 1 + (reference.accepted_position >= 0).int(), rtol=0, atol=0)+ else:+ expect = torch.searchsorted(p.cumsum(0), final, right=True)+ torch.testing.assert_close(actual.long(), expect, rtol=0, atol=0)+ assert (lengths == 1).all()+ torch.testing.assert_close(path[:, 0].cpu(), torch.arange(n, dtype=torch.int32) * width)+ if INTERPRET:+ return+ # Capture and replay the exact same probability-level implementation.+ graph = torch.cuda.CUDAGraph()+ with torch.cuda.graph(graph):+ replayed = sample_tree(*gpu_args, top_k=k, max_depth=2)+ graph.replay()+ for a, b in zip(replayed, (predict, lengths, path)):+ torch.testing.assert_close(a, b, rtol=0, atol=0)+++def test_walk_reads_recorded_proposals_through_the_request_slot_map():+ """Rows of the stores are addressed by req_index: a permuted store with the matching map gives the same result."""+ from eagle_harness.kernels.sampled_tree import sample_tree++ n, k, width = 24, 2, 3+ gen = torch.Generator().manual_seed(31)+ p = torch.softmax(torch.randn(n, 6, generator=gen), -1)+ q = torch.softmax(torch.randn(n, 4, generator=gen), -1)+ ids = torch.stack([torch.randperm(6, generator=gen)[:4] for _ in range(n)])+ draw = draw_children(q.log(), ids, k, generator=gen)+ coins = torch.rand(n, width, generator=gen)+ final = torch.rand(n, generator=gen)+ target = p[:, None, :].expand(n, width, -1).contiguous()+ next_child = torch.full((n, width), -1, dtype=torch.int32)+ next_child[:, 0] = 1+ siblings = torch.full_like(next_child, -1)+ siblings[:, 1:-1] = torch.arange(2, width, dtype=torch.int32)+ tokens = torch.cat((torch.zeros(n, 1, dtype=torch.int64), draw.tokens), dim=1)+ common = [target, torch.full((n,), True), torch.arange(k).expand(n, -1).contiguous(), tokens,+ torch.arange(n * width).view(n, width).to(torch.int32), next_child, siblings, coins, final]+ dev = "cpu" if INTERPRET else "cuda"++ def run(qs, qids, pos, valid, req):+ args = [common[0], qs, qids, pos, valid, *common[2:-2], *common[-2:]]+ args = [a.to(dev) for a in args]+ out = sample_tree(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9],+ args[10], args[11], top_k=k, max_depth=2, req_index=None if req is None else req.to(dev))+ if not INTERPRET:+ torch.cuda.synchronize()+ return [o.cpu() for o in out]++ plain = run(draw.probs[:, None, :].contiguous(), draw.token_ids[:, None, :].contiguous(), draw.positions,+ torch.full((n,), True), None)+ perm = torch.randperm(2 * n, generator=gen)[:n] # store rows, in a bigger store+ qs = torch.zeros(2 * n, 1, 4)+ qids = torch.zeros(2 * n, 1, 4, dtype=torch.int64)+ pos = torch.zeros(2 * n, k, dtype=torch.int64)+ valid = torch.zeros(2 * n, dtype=torch.bool)+ qs[perm, 0] = draw.probs+ qids[perm, 0] = draw.token_ids+ pos[perm] = draw.positions+ valid[perm] = True+ mapped = run(qs, qids, pos, valid, perm)+ for a, b in zip(plain, mapped):+ torch.testing.assert_close(a, b, rtol=0, atol=0)+++def test_width_one_has_no_proposal_node_to_load():+ from eagle_harness.kernels.sampled_tree import sample_tree++ device = "cpu" if INTERPRET else "cuda"+ target = torch.tensor([[[0.2, 0.3, 0.5]], [[0.5, 0.3, 0.2]]], device=device)+ q = torch.ones(2, 1, 2, device=device) / 2+ ids = torch.tensor([[[0, 2]], [[0, 2]]], device=device)+ empty_nodes = torch.empty(2, 0, dtype=torch.long, device=device)+ tokens = torch.zeros(2, 1, dtype=torch.long, device=device)+ index = torch.arange(2, dtype=torch.int32, device=device).view(2, 1)+ no_child = torch.full_like(index, -1)+ result = sample_tree(+ target,+ q,+ ids,+ tokens,+ torch.ones(2, dtype=torch.bool, device=device),+ empty_nodes,+ tokens,+ index,+ no_child,+ no_child,+ torch.zeros(2, 1, device=device),+ torch.tensor([0.4, 0.9], device=device),+ top_k=2,+ max_depth=1,+ )+ assert result[0].tolist() == [1, 2]+ assert result[1].tolist() == [1, 1]+ assert result[2].tolist() == [[0], [1]]+++def test_gpu_pruned_two_level_tree_keeps_node_and_proposal_mapping():+ from eagle_harness.core.sampled_tree import ChildProposals+ from eagle_harness.kernels.sampled_tree import sample_tree++ n, k, vocab, width = (12 if INTERPRET else 2048), 3, 7, 7+ gen = torch.Generator().manual_seed(981)+ draws = []+ for _ in range(3):+ logits = torch.randn(n, 4, generator=gen)+ ids = torch.stack([torch.randperm(vocab, generator=gen)[:4] for _ in range(n)])+ draws.append(draw_children(logits, ids, k, generator=gen))+ selected = torch.tensor([0, 1, 2, 3, 4, 6])+ all_tokens = torch.cat([d.tokens for d in draws], dim=1)+ tokens = torch.cat((torch.zeros(n, 1, dtype=torch.int64), all_tokens[:, selected]), dim=1)+ target = torch.softmax(torch.randn(n, width, vocab, generator=gen), dim=-1)+ coins, final = torch.rand(n, width, generator=gen), torch.rand(n, generator=gen)+ root = reject_children(target[:, 0], draws[0], coins[:, 1:4], final)+ expected = torch.zeros(n, width, dtype=torch.int32)+ expected[:, 0] = root.tokens.int()+ expected_path = torch.full((n, 3), -1, dtype=torch.int32)+ offsets = torch.arange(n) * width+ expected_path[:, 0] = offsets.int()+ expected_lengths = torch.ones(n, dtype=torch.int32)+ for row in range(n):+ parent = int(root.accepted_position[row])+ if parent < 0:+ continue+ current = parent + 1+ expected_path[row, 1] = offsets[row] + current+ expected_lengths[row] = 2+ if parent < 2:+ count, first_child = (2, 4) if parent == 0 else (1, 6)+ d = draws[parent + 1]+ proposal = ChildProposals(+ d.probs[row : row + 1],+ d.token_ids[row : row + 1],+ d.positions[row : row + 1, :count],+ d.tokens[row : row + 1, :count],+ d.scores[row : row + 1, :count],+ )+ result = reject_children(+ target[row : row + 1, current],+ proposal,+ coins[row : row + 1, first_child : first_child + count],+ final[row : row + 1],+ )+ expected[row, current] = result.tokens[0].int()+ if result.accepted_position[0] >= 0:+ current = first_child + int(result.accepted_position[0])+ expected_path[row, 2] = offsets[row] + current+ expected_lengths[row] = 3+ else:+ continue+ cdf = target[row, current].cumsum(0)+ expected[row, current] = torch.searchsorted(cdf, final[row] * cdf[-1], right=True).int()+ args = [+ target,+ torch.stack([d.probs for d in draws], dim=1),+ torch.stack([d.token_ids for d in draws], dim=1),+ torch.cat([d.positions for d in draws], dim=1),+ torch.ones(n, dtype=torch.bool),+ selected.expand(n, -1).contiguous(),+ tokens,+ torch.arange(n * width).view(n, width).int(),+ torch.tensor([1, 4, 6, -1, -1, -1, -1], dtype=torch.int32).expand(n, -1).contiguous(),+ torch.tensor([-1, 2, 3, -1, 5, -1, -1], dtype=torch.int32).expand(n, -1).contiguous(),+ coins,+ final,+ ]+ result = sample_tree(*[a.to("cpu" if INTERPRET else "cuda") for a in args], top_k=k, max_depth=3)+ for actual, reference in zip(result, (expected.flatten(), expected_lengths, expected_path)):+ torch.testing.assert_close(actual.cpu(), reference, rtol=0, atol=0)diff --git a/tests/test_sampling_check.py b/tests/test_sampling_check.pynew file mode 100644index 0000000..93e2cde--- /dev/null+++ b/tests/test_sampling_check.py@@ -0,0 +1,103 @@+# Copyright 2026 Eagle AI Corp.+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available++"""Serving distribution gates must reject missing or incomparable evidence."""++import copy+import importlib.util+import json+from pathlib import Path+import subprocess+import sys+from types import SimpleNamespace++import pytest+++def sampling_check():+ path = Path(__file__).parents[1] / "tools" / "sampling_check.py"+ spec = importlib.util.spec_from_file_location("sampling_check", path)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def artifact():+ return {+ "api": "sglang",+ "max_new_tokens": 3,+ "samples": 20,+ "settings": {+ "unrestricted": {+ "params": {"temperature": 1.0, "top_p": 1.0, "top_k": -1},+ "tokens": [[[1, 2, 3]] * 20 for _ in range(4)],+ "seconds": 1.0,+ }+ },+ "seeds": {},+ }+++def compare(module, tmp_path, ref, candidate):+ reference = tmp_path / "reference.json"+ output = tmp_path / "candidate.json"+ reference.write_text(json.dumps(ref))+ output.write_text(json.dumps(candidate))+ return module.compare(SimpleNamespace(reference=reference, candidate=output, alpha=0.01))+++def test_unrestricted_setting_exercises_temperature_one(sampling_check):+ assert sampling_check.SETTINGS["unrestricted"] == {"temperature": 1.0, "top_p": 1.0, "top_k": -1}+++def test_complete_distribution_evidence_passes(sampling_check, tmp_path):+ ref = artifact()+ assert compare(sampling_check, tmp_path, ref, copy.deepcopy(ref)) == 0++[email protected]("fault", ["empty", "missing", "refused", "parameters", "prompts", "samples", "tokens"])+def test_incomplete_distribution_evidence_fails(sampling_check, tmp_path, fault):+ ref = artifact()+ candidate = copy.deepcopy(ref)+ setting = candidate["settings"]["unrestricted"]+ if fault == "empty":+ ref["settings"].clear()+ candidate["settings"].clear()+ elif fault == "missing":+ candidate["settings"].clear()+ elif fault == "refused":+ setting.clear()+ setting["refused"] = "unsupported"+ elif fault == "parameters":+ setting["params"]["temperature"] = 0.0+ elif fault == "prompts":+ setting["tokens"].pop()+ elif fault == "samples":+ setting["tokens"][0].pop()+ elif fault == "tokens":+ setting["tokens"][0][0] = [1]+ assert compare(sampling_check, tmp_path, ref, candidate) == 1+++def test_changed_distribution_fails(sampling_check, tmp_path):+ ref = artifact()+ candidate = copy.deepcopy(ref)+ candidate["settings"]["unrestricted"]["tokens"] = [[[4, 5, 6]] * 20 for _ in range(4)]+ assert compare(sampling_check, tmp_path, ref, candidate) == 1+++def test_compare_runs_without_the_http_client(tmp_path):+ # Only `run` talks HTTP (requests); the public test env has no requests.+ path = Path(__file__).parents[1] / "tools" / "sampling_check.py"+ ref = tmp_path / "ref.json"+ ref.write_text(json.dumps(artifact()))+ code = (+ "import importlib.util, sys, types; sys.modules['requests'] = None; "+ f"spec = importlib.util.spec_from_file_location('sampling_check', {str(path)!r}); "+ "m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m); "+ f"sys.exit(m.compare(types.SimpleNamespace(reference={str(ref)!r}, candidate={str(ref)!r}, alpha=0.01)))"+ )+ out = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)+ assert out.returncode == 0, out.stderrdiff --git a/tests/test_sglang_hooks.py b/tests/test_sglang_hooks.pyindex cf6758b..408080c 100644--- a/tests/test_sglang_hooks.py+++ b/tests/test_sglang_hooks.py@@ -84,6 +84,8 @@ def test_optional_hook_accepts_absence_but_not_signature_drift(monkeypatch):(hooks.Hook(f"{algo}.no_such_hook", (), hooks.OVERRIDE, optional=True),hooks.Hook(f"{algo}.req_to_token_extra_len", ("wrong",), hooks.OVERRIDE, optional=True),+ # an optional keyword sglang does not take yet (T=1's sampling_step on the 0.1.0 engine)+ hooks.Hook(f"{algo}.req_to_token_extra_len", ("no_such_keyword",), hooks.CALL, optional=True),),)assert hooks.hook_problems() == [f"{algo}.req_to_token_extra_len('page_size',) is not ('wrong',)"]diff --git a/tests/test_sglang_sampled_worker.py b/tests/test_sglang_sampled_worker.pynew file mode 100644index 0000000..f6428d9--- /dev/null+++ b/tests/test_sglang_sampled_worker.py@@ -0,0 +1,92 @@+# Copyright 2026 Eagle AI Corp.+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available++"""The T=1 sampled tree is wired only on engines whose verify takes ``sampling_step``.++The draft worker is built the way sglang builds it: sglang's own ``EagleDraftWorker.__init__`` and+``init_attention_backends`` run, with only the distributed contexts, the draft model build and the GPU-side+harness objects replaced, so a name the harness reads from the wrong scope fails here instead of in a GPU job.+"""++from __future__ import annotations++import contextlib+from types import SimpleNamespace++import pytest+import torch++pytest.importorskip("sglang.srt.speculative.eagle_worker_v2")++from sglang.srt.runtime_context import get_context # noqa: E402+from sglang.srt.speculative import eagle_worker_v2 # noqa: E402++from eagle_harness.sglang import worker as worker_mod # noqa: E402+++def _verify_without_hook(batch, *, target_worker, req_to_token_pool, token_to_kv_pool_allocator, plan_stream,+ plan_stream_ctx, topk, num_draft_tokens, device, metadata_ready_pre_pad, finalize_tree_path,+ grammar_barrier, accept_step=None):+ return SimpleNamespace(called_with={"accept_step": accept_step})+++def _verify_with_hook(batch, *, target_worker, req_to_token_pool, token_to_kv_pool_allocator, plan_stream,+ plan_stream_ctx, topk, num_draft_tokens, device, metadata_ready_pre_pad, finalize_tree_path,+ grammar_barrier, accept_step=None, sampling_step=None):+ return SimpleNamespace(called_with={"accept_step": accept_step, "sampling_step": sampling_step})++[email protected]("engine_verify, seed", [(_verify_without_hook, None), (_verify_with_hook, 721)])+def test_draft_worker_built_like_sglang_seeds_the_sampled_tree_only_with_the_hook(monkeypatch, engine_verify, seed):+ for name in dir(eagle_worker_v2):+ if name.endswith(("_context", "_scope")) and callable(getattr(eagle_worker_v2, name)):+ monkeypatch.setattr(eagle_worker_v2, name, lambda *args, **kwargs: contextlib.nullcontext())+ model = SimpleNamespace(+ config=SimpleNamespace(hidden_size=8),+ model=SimpleNamespace(fc=SimpleNamespace(in_features=16)),+ get_attention_sliding_window_size=lambda: None,+ )+ runner = SimpleNamespace(model=model, dtype=torch.float32, model_config=SimpleNamespace(hf_config=SimpleNamespace()))+ monkeypatch.setattr(+ eagle_worker_v2, "TpModelWorker", lambda **kwargs: SimpleNamespace(model_runner=runner, init_attention_backends=lambda: None)+ )+ monkeypatch.setattr(eagle_worker_v2, "get_plan_stream", lambda device: (None, None))+ monkeypatch.setattr(eagle_worker_v2, "get_pp_stage_load_group", lambda: None)+ built = {}+ monkeypatch.setattr(worker_mod, "run_eagle_verify", engine_verify)+ monkeypatch.setattr(worker_mod, "DraftBackendFactory", lambda *args: SimpleNamespace(create_draft_extend_backend=lambda: None))+ for name in ("DraftTree", "DraftRowAttention", "DraftExtend"):+ monkeypatch.setattr(worker_mod, name, lambda *args, **kwargs: SimpleNamespace())+ steps = object()+ monkeypatch.setattr(worker_mod, "DraftSteps", lambda *args, **kwargs: built.update(kwargs) or steps)+ target = SimpleNamespace(random_seed=721, model_runner=SimpleNamespace(model_config=SimpleNamespace(context_len=64)))+ policy = SimpleNamespace(intensity=None, max_history_verify_num=16, launch_depths=())+ with get_context().override_server_args(+ speculative_eagle_topk=4, speculative_num_steps=6, speculative_num_draft_tokens=16, device="cpu",+ max_running_requests=8,+ ):+ draft = worker_mod.HarnessDraftWorker(None, 0, 0, target, policy=policy)+ draft.init_attention_backends()+ assert built == {"sampled_seed": seed}+ assert draft.steps is steps # every sglang-built draft worker has its DraftSteps before the first round++[email protected]("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)+ monkeypatch.setattr(worker_mod, "fused_accept_supported", lambda *args: False)+ sampled = None if engine_verify is _verify_without_hook else SimpleNamespace(active=active, sample=lambda *args: args)+ worker = SimpleNamespace(+ _draft_worker=SimpleNamespace(steps=SimpleNamespace(sampled=sampled)),+ topk=4,+ token_to_kv_pool_allocator=SimpleNamespace(get_kvcache=lambda: None),+ **dict.fromkeys(("target_worker", "req_to_token_pool", "plan_stream", "plan_stream_ctx", "device")),+ )+ batch = SimpleNamespace(spec_info="verify-input", enable_overlap=False)+ result, staged = worker_mod.EagleHarnessWorker._verify(worker, batch, 8, None)+ assert not staged+ step = result.called_with.get("sampling_step")+ if active:+ assert step("target", "coins", "final") == ("verify-input", "target", "coins", "final")+ else:+ assert step is Nonediff --git a/tests/test_worker_rounds.py b/tests/test_worker_rounds.pyindex 9b78a29..7e64312 100644--- a/tests/test_worker_rounds.py+++ b/tests/test_worker_rounds.py@@ -209,6 +209,36 @@ def make_worker(modules, monkeypatch, *, calibration=None, schedule=None, nativereturn worker, calls, fence+def test_sampled_tree_follows_the_batch_and_never_verifies_roots_drafted_without_it(modules, monkeypatch):+ worker, _, _ = make_worker(modules, monkeypatch, native=False)+ worker.topk = 4+ invalidated = []+ sampled = SimpleNamespace(active=False, root_valid=torch.ones(8, dtype=torch.bool), invalidate=invalidated.append)+ worker._draft_worker.steps = SimpleNamespace(sampled=sampled)+ monkeypatch.setattr(modules.base, "forward_batch_generation", lambda self, *args: "prefill", raising=False)++ def batch(temperature, mode=Mode.DECODE):+ out = make_batch(Request(), Request(), mode=mode)+ for request in out.reqs:+ request.sampling_params = SimpleNamespace(temperature=temperature)+ out.has_grammar = False+ out.sampling_info = SimpleNamespace(+ is_all_greedy=False, acc_additive_penalties=None, acc_scaling_penalties=None, has_watermark_candidates=False+ )+ return out++ worker.forward_batch_generation(batch(1.0))+ assert sampled.active and not sampled.root_valid.any() # the roots came from the greedy draft extend+ sampled.root_valid.fill_(True) # this round's sampled extend recorded the next roots+ worker.forward_batch_generation(batch(1.0))+ assert sampled.active and sampled.root_valid.all()+ worker.forward_batch_generation(batch(0.7))+ assert not sampled.active and not sampled.root_valid.any()+ prefill = batch(1.0, mode=Mode.EXTEND)+ assert worker.forward_batch_generation(prefill) == "prefill"+ assert invalidated == [prefill.req_pool_indices]++@pytest.mark.parametrize("overlap", [False, True])@pytest.mark.parametrize("calibrating", [False, True])def test_native_decode_orders_barrier_calibration_publication_and_wait(modules, monkeypatch, tmp_path, calibrating, overlap):diff --git a/tools/sampling_check.py b/tools/sampling_check.pyindex 2ebe65c..84bf353 100644--- a/tools/sampling_check.py+++ b/tools/sampling_check.py@@ -46,8 +46,6 @@ import sysimport timefrom typing import Dict, List, Optional, Sequence, Tuple-import requests-PROMPTS = ("Here is a list of ten random animals:","Once upon a time, in a",@@ -55,6 +53,7 @@ PROMPTS = ("The weather today is",)SETTINGS: Dict[str, dict] = {+ "unrestricted": {"temperature": 1.0, "top_p": 1.0, "top_k": -1},"temperature": {"temperature": 0.7},"top_k_top_p": {"temperature": 1.0, "top_k": 8, "top_p": 0.7},"min_p": {"temperature": 1.0, "min_p": 0.05},@@ -67,6 +66,7 @@ POOL = 10 # cells seen fewer times than this in both runs together are pooleddef generate(api: str, base: str, model: Optional[str], prompt: List[int], params: dict, max_new: int, seed=None):"""One completion's output token ids (and sglang's ``spec_*`` meta info)."""+ import requests # only the HTTP client needs it; compare runs in test envs without itif api == "sglang":sp = {"max_new_tokens": max_new, "ignore_eos": True, **params}if seed is not None:@@ -86,6 +86,7 @@ def generate(api: str, base: str, model: Optional[str], prompt: List[int], paramdef vllm_spec_counters(base: str) -> Dict[str, float]:"""vLLM's speculative decoding counters (drafts, accepted tokens), from /metrics."""+ import requestscounters: Dict[str, float] = collections.defaultdict(float)for line in requests.get(f"{base}/metrics", timeout=60).text.splitlines():if line.startswith("vllm:spec_decode_num_") and "_total" in line.split("{")[0]:@@ -94,13 +95,22 @@ def vllm_spec_counters(base: str) -> Dict[str, float]:def run(args) -> int:+ import requestsfrom transformers import AutoTokenizertokenizer = AutoTokenizer.from_pretrained(args.tokenizer)base = f"http://127.0.0.1:{args.port}"model = requests.get(f"{base}/v1/models", timeout=60).json()["data"][0]["id"] if args.api == "vllm" else Noneprompts = [tokenizer.encode(p, add_special_tokens=False) for p in PROMPTS]- result: dict = {"api": args.api, "max_new_tokens": args.max_new_tokens, "settings": {}, "seeds": {}}+ result: dict = {+ "api": args.api,+ "max_new_tokens": args.max_new_tokens,+ "samples": args.samples,+ "concurrency": args.concurrency,+ "prompt_ids": prompts,+ "settings": {},+ "seeds": {},+ }pool = concurrent.futures.ThreadPoolExecutor(args.concurrency)for name in args.settings.split(","):params = SETTINGS[name]@@ -231,18 +241,45 @@ def homogeneity(ref: Sequence, test: Sequence) -> Tuple[float, float, int]:return chi2_sf(stat, len(cells) - 1), tv, len(cells)+def validate_pair(ref: dict, cand: dict) -> None:+ """Reject partial evidence before a statistical test can silently omit it."""+ if not ref["settings"] or ref["settings"].keys() != cand["settings"].keys():+ raise ValueError("reference and candidate must contain the same nonempty settings")+ length = ref["max_new_tokens"]+ if length < JOINT or cand["max_new_tokens"] != length:+ raise ValueError("matched token lengths must cover the joint test")+ if ref.get("prompt_ids") != cand.get("prompt_ids"):+ raise ValueError("reference and candidate prompt token ids differ")+ for name in ref["settings"]:+ r, c = ref["settings"][name], cand["settings"][name]+ if "refused" in r or "refused" in c:+ raise ValueError(f"{name}: refused setting is not distribution evidence")+ if r["params"] != c["params"]:+ raise ValueError(f"{name}: sampling parameters differ")+ if len(r["tokens"]) != len(PROMPTS) or len(c["tokens"]) != len(PROMPTS):+ raise ValueError(f"{name}: missing prompt results")+ for r_tokens, c_tokens in zip(r["tokens"], c["tokens"]):+ if not r_tokens or len(r_tokens) != len(c_tokens):+ raise ValueError(f"{name}: empty or unequal sample counts")+ for artifact, tokens in ((ref, r_tokens), (cand, c_tokens)):+ if len(tokens) != artifact.get("samples", len(tokens)):+ raise ValueError(f"{name}: sample count differs from the requested count")+ if any(len(ids) != length for ids in tokens):+ raise ValueError(f"{name}: incomplete output token sequence")++def compare(args) -> int:with open(args.reference, encoding="utf-8") as f:ref = json.load(f)with open(args.candidate, encoding="utf-8") as f:cand = json.load(f)+ try:+ validate_pair(ref, cand)+ except (KeyError, TypeError, ValueError) as error:+ print(f"INVALID distribution evidence: {error}")+ return 1tests = [] # (setting, prompt, what, p, tv, cells)for name, entry in cand["settings"].items():- if "refused" in entry:- print(f"{name:12s} REFUSED by the server: {entry['refused']}")- continue- if name not in ref["settings"]:- continuefor i, (r_tokens, c_tokens) in enumerate(zip(ref["settings"][name]["tokens"], entry["tokens"])):k = min(len(r_tokens[0]), len(c_tokens[0]))r_joint = [tuple(t[:JOINT]) for t in r_tokens]