Skip to content

Official Inference Code of EAGLE-4

Release 0.1.5: SGLang speed and sampled-tree fixes

Seyfal Sultanova244aa249f72
diff --git a/docs/faq.md b/docs/faq.md
index 93316ce..9295e67 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -25,8 +25,9 @@ so only the draft depth adapts per round.
- Warm the server up first. The first requests after a start compile kernels and seed the live costs. On
4× B300 at one request (SGLang, eagle-harness 0.1.2, started with `--skip-server-warmup`), the first request
after a start decoded at 63 to 85 tokens/s in three starts. The same request after warm-up decoded at 910 to
- 915 tokens/s. Send a few requests that look like your workload, or run the workload once, before timing.
- Restarts reuse the caches under `~/.cache/eagle-harness/costs`.
+ 915 tokens/s. Before timing, run one untimed pass of your workload at each concurrency
+ ([what to warm up](#what-should-i-warm-up-before-timing-a-benchmark)). Restarts reuse the caches under
+ `~/.cache/eagle-harness/costs`.
- Compare against the same engine and flags. Start the server without speculation from the same command minus
the `--speculative-*` flags. Keep `--mamba-ssm-dtype`, the attention backend, the page size and the CUDA graph
settings identical, because they change the speed of plain decoding too.
@@ -85,8 +86,9 @@ do not establish distribution equivalence for every model and workload.
verified as chains using the host rejection sampler, which can accept fewer tokens. This fallback is not a
claim of token-identical output across different numerical execution shapes.
- sglang: sampled requests go through sglang's own tree speculative sampling. Two settings need an sglang build with
- the verify filter fix: min-p, and top-k combined with top-p. Older builds ignore min-p in verify and cut top-p after
- top-k.
+ the verify filter fix, which the pinned engine has: min-p, and top-k combined with top-p. Older builds ignore min-p
+ in verify and cut top-p after top-k. The temperature-1 sampled tree draws its proposals with the request's top-k,
+ top-p and min-p, applied jointly as sglang's sampler applies them.
Penalties use sglang's relaxed form (counts of committed tokens only), as in sglang's own EAGLE, so they are not
exact. Seeds need `--enable-deterministic-inference`.
@@ -102,6 +104,36 @@ NVIDIA from sm_80 (A100) and AMD CDNA2 to CDNA4 through the Triton kernels, with
newer NVIDIA GPUs. Serving measurements cover B300 and SGLang on MI355X. Other architectures have compilation
coverage, not serving qualification. See [kernels](kernels.md).
+## What should I warm up before timing a benchmark?
+
+Run one untimed pass of your workload at each concurrency you plan to measure, then time a separate pass.
+Use the same prompt and output lengths, sampling settings and server flags for both passes. The first requests
+compile kernels and fill cost caches for the batch shapes the workload exercises. A single request does not
+warm the shapes used by a concurrent workload.
+
+Repeat this warm-up after each server start, including restarts with saved caches. Warm both the EAGLE-4 server
+and its same-engine no-speculation baseline. To isolate the effect of speculation, keep non-speculation settings
+matched, including the attention backend, recurrent-state dtype, page size and CUDA graph settings. Measure at the
+temperature you serve, and report decoding throughput separately from prefill latency or time to first token.
+
+When reproducing a published ratio, use its documented no-speculation configuration and report any differences
+between the servers. For example, the [AMD measurement](quickstart-amd.md#installed-wheel-qualification) uses
+the ordinary overlapping scheduler and twice the Mamba cache cap for its no-speculation control.
+
+The [candidate high-load measurement](support-matrix.md#candidate-high-load), source 1, illustrates why you
+should distinguish a first machine start from a warm restart. It uses SGLang TP4 with Qwen3.8-27B,
+automatic chain widths and a running cap of 512. At concurrency 64, the workload has 128 first turns with up to
+256 new tokens per turn. Each ratio divides EAGLE-4 throughput by the same engine's no-speculation throughput,
+so a higher ratio is better.
+
+| Cache condition at concurrency 64 | Throughput relative to no speculation |
+|---|---|
+| First server start on the machine, compiling kernels during requests | 0.78× |
+| Warm restarts with a saved policy cache, three starts | 1.07× |
+
+These are candidate measurements, not a speed guarantee for another setup. If cold-start performance matters
+to your application, report it separately rather than including it in a warm-throughput average.
+
## How do I cite it?
Cite the EAGLE-4 paper. `CITATION.cff` at the repository root has the entry, and GitHub shows it under "Cite this
diff --git a/docs/kernels.md b/docs/kernels.md
index 8a51fbc..25922a5 100644
--- a/docs/kernels.md
+++ b/docs/kernels.md
@@ -33,7 +33,7 @@ coverage, not serving qualification. Native CUDA builds apply only to NVIDIA tar
|---|---|---|
| candidate head: shard top-k, exact re-scoring of candidates (fp32 products), candidate tail | `candidate_ops`, `gather_dot`, `candidate_triton`, `csrc/candidate.cu` | every draft step and draft extend |
| draft tree step: scores, next frontier, ancestors, the cost model's work deltas | `tree_step` | every draft step |
-| draft row attention: each row's sliding window plus its own tree ancestors, split over the keys (the split count follows the SM count and the draft heads per rank, fixed per server) | `sglang/row_attention.py`, `vllm/draft_attention.py` | every draft step and draft extend |
+| draft row attention: each row's sliding window plus its own tree ancestors, split over the keys (the split count follows the SM count and the batch's (request, head) programs, fixed per captured batch size) | `sglang/row_attention.py`, `vllm/draft_attention.py` | every draft step and draft extend |
| GDN tree verify: ancestor tables, tree causal conv1d, tree gated delta rule recurrence | `gdn_tree`, `gdn_tree_gluon` | every verify of a hybrid (GDN) target |
| Mamba2 tree verify: ancestor tables, tree causal conv1d | `gdn_tree`, `gdn_tree_conv` | every verify of a Mamba2 hybrid (NemotronH) target on sglang |
| tree verify attention, split over the committed context | `vllm/verify_attention.py` | every verify on vLLM |
diff --git a/docs/quickstart-amd.md b/docs/quickstart-amd.md
index 5db4a2c..560ea2f 100644
--- a/docs/quickstart-amd.md
+++ b/docs/quickstart-amd.md
@@ -85,8 +85,9 @@ curl --fail http://127.0.0.1:30000/generate \
-d '{"text":"Explain how a hash table works.","sampling_params":{"temperature":0,"max_new_tokens":128}}'
```
-The response must contain generated text and token metadata. The first request includes cold work because
-the measured launch skips server warmup. Repeat it before timing. In Docker, bind the server to `0.0.0.0`
+The response must contain generated text and token metadata. Before timing, run one untimed pass of your workload
+at each concurrency to compile kernels and fill cost caches
+([benchmark warm-up](faq.md#what-should-i-warm-up-before-timing-a-benchmark)). In Docker, bind the server to `0.0.0.0`
inside the container while publishing only the loopback host port.
Stop the server with Ctrl-C before changing its graph sizes or starting another GPU process.
@@ -103,7 +104,8 @@ The no-spec control is our own installed engine on the same MI355X, target weigh
with speculation disabled and the ordinary overlapping scheduler. It was measured once per
concurrency with twice the Mamba cache cap. Measurements use 44 conversations / 60 turns,
1,024 maximum new tokens, greedy decoding and a separate warmup pass. At concurrency 1,
-the running-request cap, decode graph batch sizes and Mamba cache cap are all reduced to 1.
+both servers use a running-request cap and decode graph batch size of 1. The Mamba cache cap is 1 for EAGLE-4
+and 2 for the no-spec control.
The packaged MI355X profile was selected without a source overlay or profile override.
Each start also passed 20 greedy prompts against an installed no-spec control. Both C1 starts
diff --git a/docs/quickstart-sglang.md b/docs/quickstart-sglang.md
index bee7e22..968f9df 100644
--- a/docs/quickstart-sglang.md
+++ b/docs/quickstart-sglang.md
@@ -77,8 +77,9 @@ sglang serve --model-path Qwen/Qwen3.8-27B --tp-size 4 --dtype bfloat16 \
--speculative-algorithm-config '{"mode":"serve"}'
```
-The benchmark warmed the server from its client, hence `--skip-server-warmup`: the first request after this start
-compiles kernels and seeds the costs. Keep CUDA graph padding enabled, and do not add
+Before timing, run one untimed pass of your workload at each concurrency to compile kernels and fill cost caches
+([benchmark warm-up](faq.md#what-should-i-warm-up-before-timing-a-benchmark)). The measured command uses client
+warm-up with `--skip-server-warmup`. Keep CUDA graph padding enabled, and do not add
`--disable-cuda-graph-padding`. `--max-running-requests 32` is the tree default; set a larger cap, up to 512, for
larger batches, or serve with the [high-load recipe](#high-load).
diff --git a/docs/quickstart-vllm.md b/docs/quickstart-vllm.md
index f8c4944..81991c4 100644
--- a/docs/quickstart-vllm.md
+++ b/docs/quickstart-vllm.md
@@ -46,7 +46,9 @@ curl http://localhost:8000/v1/chat/completions -H 'Content-Type: application/jso
-d '{"model": "Qwen/Qwen3.8-27B", "messages": [{"role": "user", "content": "Explain how a hash table works."}], "max_tokens": 256}'
```
-The response holds the generated message. Send a few requests before you measure speed.
+The response holds the generated message. Before timing, run one untimed pass of your workload at each concurrency
+to compile kernels and fill any live cost caches
+([benchmark warm-up](faq.md#what-should-i-warm-up-before-timing-a-benchmark)).
## The measured recipe
diff --git a/eagle_harness/core/draft_tree.py b/eagle_harness/core/draft_tree.py
index 28b98d1..72776ca 100644
--- a/eagle_harness/core/draft_tree.py
+++ b/eagle_harness/core/draft_tree.py
@@ -208,6 +208,17 @@ class DraftTree:
"""Record the draft KV slots ``[bs, K]`` the depth-``step`` frontier writes."""
self.ancestors[:bs, :, step - 1] = slots.to(torch.int32)
+ def keep_rows(self, rows: torch.Tensor) -> None:
+ """Keep the requests at batch positions ``rows`` (in that order) as rows ``0..len(rows)-1``: a drafted tree
+ then serves the batch that remains once some of its requests left. Rows are independent, so the kept rows
+ are the tree those requests alone would have grown."""
+ n, k = rows.numel(), self.shape.top_k
+ per_request = (self.root_probs, self.root_tokens, self.root_hidden, self.scores, self.tokens, self.parents,
+ self.front_scores, self.ancestors, self.best, self.best_prev, self.layer_top, self.delta_rows)
+ per_node = (self.front_tokens.view(self.max_bs, k), self.front_hidden.view(self.max_bs, k, -1))
+ for buf in per_request + per_node:
+ buf[:n] = buf.index_select(0, rows)
+
def step(self, bs: int, step: int, probs: torch.Tensor, tokens: torch.Tensor, hidden: torch.Tensor) -> None:
"""Add the children of the depth-``step`` frontier (``1 <= step < max_depth``).
diff --git a/eagle_harness/core/live_costs.py b/eagle_harness/core/live_costs.py
index 6ff8b00..8b925f6 100644
--- a/eagle_harness/core/live_costs.py
+++ b/eagle_harness/core/live_costs.py
@@ -144,13 +144,29 @@ class LiveCosts:
seed_samples: int = 3
alpha: float = 0.05
cells: Dict[Tuple[int, int, int], Cell] = field(default_factory=dict) # (bucket, width, interval)
+ # Sample counts per (bucket, width) and the ready buckets, indexed from ``cells`` (rebuilt when it is replaced):
+ # the drafter asks every round, and a scan of every cell costs far more than the answer.
+ _counts: Dict[Tuple[int, int], int] = field(default_factory=dict, init=False, repr=False, compare=False)
+ _ready: set = field(default_factory=set, init=False, repr=False, compare=False)
+ _indexed: Optional[dict] = field(default=None, init=False, repr=False, compare=False)
def interval(self, context: int) -> int:
"""Context interval of an average committed length (the tables' ``interval_index``)."""
return min(max((context - self.context_step) // self.context_step, 0), self.context_intervals - 1)
+ def _index(self) -> None:
+ """Bring the counts and ready buckets up to date with ``cells`` (a new dict after a load or a TP sync)."""
+ if self._indexed is self.cells:
+ return
+ self._indexed = self.cells
+ self._counts = {}
+ for (b, w, _), c in self.cells.items():
+ self._counts[b, w] = self._counts.get((b, w), 0) + c.samples
+ self._ready = {b for b, _ in self._counts if self._is_ready(b)}
+
def _samples(self, bucket: int, width: int) -> int:
- return sum(c.samples for (b, w, _), c in self.cells.items() if b == bucket and w == width)
+ self._index()
+ return self._counts.get((bucket, width), 0)
def seed_width(self, bucket: int) -> Optional[int]:
"""The verify width the next round at ``bucket`` must force, None once the bucket is seeded.
@@ -163,20 +179,46 @@ class LiveCosts:
return width
return None
+ def _is_ready(self, bucket: int) -> bool:
+ return self.seed_width(bucket) is None and self._samples(bucket, DRAFT_WIDTH) >= self.seed_samples
+
def ready(self, bucket: int) -> bool:
"""Whether the bucket's cells price every captured width and the draft step."""
- return self.seed_width(bucket) is None and self._samples(bucket, DRAFT_WIDTH) >= self.seed_samples
+ self._index()
+ return bucket in self._ready
+
+ def _bracket(self, bucket: int) -> Optional[Tuple[int, int]]:
+ """The nearest ready buckets below and above an unready ``bucket``, None unless both exist."""
+ if self.ready(bucket):
+ return None
+ below = max((b for b in self._ready if b < bucket), default=None)
+ above = min((b for b in self._ready if b > bucket), default=None)
+ return None if below is None or above is None else (below, above)
+
+ def priced(self, bucket: int) -> bool:
+ """Whether the bucket has a table without a seed sweep: it is ready, or it lies between two ready
+ buckets, which price it by linear interpolation in the batch size (:meth:`tables`).
+
+ Verify and draft costs grow smoothly with the batch size, so a bucket the load visits only briefly (the
+ sizes a batch drains through) is priced from its neighbours instead of forcing narrow verify widths on its
+ served rounds; its own served rounds refine the widths they run.
+ """
+ return self.ready(bucket) or self._bracket(bucket) is not None
def record(self, bucket: int, width: int, context: int, us: float) -> None:
"""Add one served timing (``width`` 0: one draft step)."""
if not math.isfinite(us) or us <= 0:
return
+ self._index()
cell = self.cells.setdefault((bucket, width, self.interval(context)), Cell())
if cell.samples < self.seed_samples:
cell.us = us if cell.samples == 0 else min(cell.us, us)
else:
cell.us += self.alpha * (min(us, OUTLIER_RATIO * cell.us) - cell.us)
cell.samples += 1
+ self._counts[bucket, width] = self._counts.get((bucket, width), 0) + 1
+ if bucket not in self._ready and self._is_ready(bucket):
+ self._ready.add(bucket)
# ---------------------------------------------------------------- tables
def _value(self, bucket: int, width: int, interval: int) -> Optional[float]:
@@ -191,20 +233,51 @@ class LiveCosts:
def verify_us(self, bucket: int, width: int) -> Optional[float]:
"""The priced verify of ``width`` tokens per request at ``bucket`` (shortest context first), None untimed."""
- return self._value(bucket, width, 0)
-
- def tables(self) -> Dict[int, BatchCostTable]:
- """One table per ready bucket (the cost model's input), from the current cells."""
+ value = self._value(bucket, width, 0)
+ if value is None and self._bracket(bucket) is not None:
+ value = self._priced(bucket, width, 0)
+ return value
+
+ def _width_value(self, bucket: int, width: int, interval: int) -> float:
+ """A ready bucket's cost at ``width``, linear between its measured widths (they include 1 and the widest)."""
+ if width == DRAFT_WIDTH or width in self.widths(bucket):
+ return self._value(bucket, width, interval) or 0.0
+ widths = sorted(self.widths(bucket))
+ lo = max((w for w in widths if w < width), default=widths[0])
+ hi = min((w for w in widths if w > width), default=widths[-1])
+ lo_us, hi_us = self._value(bucket, lo, interval) or 0.0, self._value(bucket, hi, interval) or 0.0
+ return lo_us if hi == lo else lo_us + (width - lo) / (hi - lo) * (hi_us - lo_us)
+
+ def _priced(self, bucket: int, width: int, interval: int) -> float:
+ """An unready bucket's cost: its own fully sampled cell at this interval, else linear in the batch size
+ between the ready buckets around it (:meth:`priced`)."""
+ own = self.cells.get((bucket, width, interval))
+ if own is not None and own.samples >= self.seed_samples:
+ return own.us
+ bracket = self._bracket(bucket)
+ if bracket is None:
+ raise ValueError(f"batch bucket {bucket} has no ready buckets on both sides")
+ below, above = bracket
+ lo_us, hi_us = self._width_value(below, width, interval), self._width_value(above, width, interval)
+ return lo_us + (bucket - below) / (above - below) * (hi_us - lo_us)
+
+ def tables(self, also: Sequence[int] = ()) -> Dict[int, BatchCostTable]:
+ """One table per priced bucket that has cells or is in ``also`` (the cost model's input), from the current
+ cells: a ready bucket's own, an unready one's interpolated from its neighbours where it lacks them."""
tables: Dict[int, BatchCostTable] = {}
- for bucket in sorted({b for b, _, _ in self.cells}):
- if not self.ready(bucket):
+ for bucket in sorted({b for b, _, _ in self.cells} | set(also)):
+ if self.ready(bucket):
+ value = self._value
+ elif self._bracket(bucket) is not None:
+ value = self._priced
+ else:
continue
widths = sorted(self.widths(bucket))
intervals: List[IntervalCost] = []
ratios: List[float] = []
for i in range(self.context_intervals):
- target = [self._value(bucket, w, i) or 0.0 for w in widths]
- draft = self._value(bucket, DRAFT_WIDTH, i) or 0.0
+ target = [value(bucket, w, i) or 0.0 for w in widths]
+ draft = value(bucket, DRAFT_WIDTH, i) or 0.0
intervals.append(IntervalCost(_curve(target, [w - 1 for w in widths]), _curve([draft], [0])))
ratios.append(round(target[0] / draft, 4))
tables[bucket] = BatchCostTable(
diff --git a/eagle_harness/core/sampled_tree.py b/eagle_harness/core/sampled_tree.py
index 7370721..2ca083e 100644
--- a/eagle_harness/core/sampled_tree.py
+++ b/eagle_harness/core/sampled_tree.py
@@ -35,6 +35,31 @@ class RejectionResult(NamedTuple):
accepted_position: torch.Tensor # [rows], draw index, or -1 for a residual draw
+def filter_proposal_logits(
+ logits: torch.Tensor,
+ temperature: torch.Tensor,
+ top_k: torch.Tensor,
+ top_p: torch.Tensor,
+ min_p: torch.Tensor,
+) -> torch.Tensor:
+ """Apply the request's temperature and filter settings to the draft candidate logits.
+
+ Top-k and top-p cut the unfiltered draft probabilities, and min-p drops what is below ``min_p`` times the
+ most likely. Removed candidates get ``-inf`` (q = 0). The draft and target can retain different tokens under
+ the same settings. Recursive rejection uses the recorded q and the target p, including their differing support.
+ Per-row settings are ``[rows]`` tensors; ties rank by candidate index.
+ """
+ scaled = logits.float() / temperature.float()[:, None]
+ probs = torch.softmax(scaled, dim=-1)
+ order = torch.sort(-probs, dim=-1, stable=True).indices
+ rank = torch.empty_like(order)
+ rank.scatter_(1, order, torch.arange(logits.shape[1], device=logits.device).expand_as(order).contiguous())
+ above = (probs.gather(1, order).cumsum(dim=-1) - probs.gather(1, order)).gather(1, rank)
+ keep = (rank < top_k[:, None]) & (above < top_p[:, None])
+ keep &= probs >= min_p[:, None] * probs.amax(dim=-1, keepdim=True)
+ return scaled.masked_fill(~keep, float("-inf"))
+
+
def draw_children(
logits: torch.Tensor,
token_ids: torch.Tensor,
diff --git a/eagle_harness/kernels/sampled_draw.py b/eagle_harness/kernels/sampled_draw.py
index 9a6604d..5fa5cb6 100644
--- a/eagle_harness/kernels/sampled_draw.py
+++ b/eagle_harness/kernels/sampled_draw.py
@@ -30,6 +30,7 @@ def _sample_children(
OUT_TOKENS,
SCORES,
REQ,
+ FILTERS,
seed,
launch,
stride_l,
@@ -43,6 +44,8 @@ def _sample_children(
K: tl.constexpr,
BLOCK: tl.constexpr,
USE_UNIFORMS: tl.constexpr,
+ USE_FILTERS: tl.constexpr,
+ CHUNK: tl.constexpr,
):
row = tl.program_id(0)
req = row // rows_per_req
@@ -52,10 +55,36 @@ def _sample_children(
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)
+ if USE_FILTERS:
+ # The request's sampling settings (see filter_proposal_logits): 1/temperature, top-k, top-p, min-p.
+ inv_t = tl.load(FILTERS + store * 4)
+ logits = logits * inv_t
peak = tl.max(logits, 0)
e = tl.exp(logits - peak)
e = tl.where(mask, e, 0.0)
- probs = e / tl.sum(e, 0)
+ total = tl.sum(e, 0)
+ probs = e / total
+ keep = mask
+ if USE_FILTERS:
+ top_k = tl.load(FILTERS + store * 4 + 1)
+ top_p = tl.load(FILTERS + store * 4 + 2)
+ min_p = tl.load(FILTERS + store * 4 + 3)
+ # Rank and the mass ranked above each candidate, ties broken by index, chunk by chunk.
+ rank = tl.zeros((BLOCK,), dtype=tl.float32)
+ above = tl.zeros((BLOCK,), dtype=tl.float32)
+ for j0 in tl.static_range(0, BLOCK, CHUNK):
+ cj = j0 + tl.arange(0, CHUNK)
+ lj = tl.load(LOGITS + row * stride_l + cj, mask=cj < NC, other=float("-inf")).to(tl.float32) * inv_t
+ pj = tl.where(cj < NC, tl.exp(lj - peak), 0.0) / total
+ higher = (pj[None, :] > probs[:, None]) | ((pj[None, :] == probs[:, None]) & (cj[None, :] < c[:, None]))
+ higher = higher & (cj[None, :] != c[:, None]) & (cj[None, :] < NC)
+ rank += tl.sum(higher.to(tl.float32), 1)
+ above += tl.sum(tl.where(higher, pj[None, :], 0.0), 1)
+ # Apply the request's joint filters to the draft probabilities, not the target's token support.
+ keep = (rank < top_k) & (above < top_p) & (probs >= min_p * tl.max(probs, 0))
+ keep = mask & keep
+ kept = tl.where(keep, probs, 0.0)
+ probs = tl.where(tl.sum(keep.to(tl.int32), 0) == NC, probs, kept / tl.sum(kept, 0))
if USE_UNIFORMS:
u = tl.load(UNIF + row * NC + c, mask=mask, other=0.5)
else:
@@ -72,6 +101,9 @@ def _sample_children(
# 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))
+ # A filtered candidate (q = 0) ranks below every kept one but stays distinct from the drawn and padding slots, so
+ # draws past the kept support land on distinct inert candidates.
+ keys = tl.where(keep, keys, -1e30)
keys = tl.where(mask, keys, float("-inf"))
qbase = Q + store * q_batch_stride + (q_slot + local) * NC
tl.store(qbase + c, probs, mask=mask)
@@ -109,6 +141,7 @@ def sample_children(
rows_per_req: int,
uniforms: Optional[torch.Tensor] = None,
req_index: Optional[torch.Tensor] = None,
+ filters: 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)``.
@@ -117,7 +150,9 @@ def sample_children(
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).
+ row in the stores (default: the batch position). ``filters`` (fp32 ``[store rows, 4]``: 1/temperature, top-k,
+ top-p, min-p per store row) apply the request's sampling settings to q; the draw then
+ equals :func:`draw_children`'s on :func:`~eagle_harness.core.sampled_tree.filter_proposal_logits`.
"""
rows, nc = logits.shape
if token_ids.shape != logits.shape or not 1 <= count <= nc or rows % rows_per_req:
@@ -131,6 +166,9 @@ def sample_children(
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")
+ if filters is not None and (filters.dtype != torch.float32 or filters.dim() != 2 or filters.shape[1] != 4
+ or not filters.is_contiguous()):
+ raise ValueError("filters must be a contiguous fp32 [rows, 4] store (1/temperature, top-k, top-p, min-p)")
device = logits.device
scores = torch.empty((rows, count), dtype=torch.float32, device=device)
tokens = torch.empty((rows, count), dtype=torch.int64, device=device)
@@ -147,6 +185,7 @@ def sample_children(
tokens,
scores,
req_index,
+ filters if filters is not None else logits,
int(seed) & 0xFFFFFFFF,
int(launch),
logits.stride(0),
@@ -160,6 +199,8 @@ def sample_children(
K=count,
BLOCK=triton.next_power_of_2(nc),
USE_UNIFORMS=uniforms is not None,
+ USE_FILTERS=filters is not None,
+ CHUNK=min(32, triton.next_power_of_2(nc)),
num_warps=4 if nc <= 256 else 8,
)
return scores, tokens
diff --git a/eagle_harness/sglang/drafter.py b/eagle_harness/sglang/drafter.py
index 0531a6a..c1fd55e 100644
--- a/eagle_harness/sglang/drafter.py
+++ b/eagle_harness/sglang/drafter.py
@@ -26,6 +26,7 @@ decoding; the draft extend still runs, so the draft stays current).
from __future__ import annotations
+from collections import Counter
import copy
from dataclasses import dataclass
import logging
@@ -58,6 +59,9 @@ logger = logging.getLogger(__name__)
# rewritten every 16th refresh and when a bucket's seed sweep completes.
LIVE_REFRESH_ROUNDS = 64
LIVE_SAVE_REFRESHES = 16
+# Rounds a batch bucket priced from the buckets around it serves before it is seeded itself: a bucket the load only
+# passes through (a draining batch) stays interpolated, one it dwells in pays for its own seed sweep.
+LIVE_SEED_AFTER_ROUNDS = LIVE_REFRESH_ROUNDS
def spin_wait(event: torch.cuda.Event) -> None:
@@ -94,11 +98,13 @@ class RoundTimer:
def drain(self, *, wait: bool) -> None:
"""Feed the completed spans to the live costs; ``wait`` blocks for the rest (seed rounds, so every
- TP rank records the same rounds and their cells agree)."""
+ TP rank records the same rounds and their cells agree). A span of a bucket that is not ready yet is always
+ waited for: which buckets are ready decides which ones are priced from their neighbours, so it must
+ change on the same round on every rank."""
left = []
for span in self._pending:
start, end, bucket, width, context, count = span
- if wait:
+ if wait or not self.live.ready(bucket):
end.synchronize()
elif not end.query():
left.append(span)
@@ -233,6 +239,8 @@ class DynamicDrafter:
self._save_cells = save_cells
self._rounds = 0
self._seeding: Optional[Tuple[int, int]] = None # (bucket, context) of a seed round's draft steps
+ self._interpolated = False # the last round's bucket was priced from the buckets around it
+ self._visits: Counter = Counter() # rounds served per batch bucket
self._unpriced: set = set() # buckets whose live costs the cost model rejects (it keeps the fixed shape)
self._trivial = build_trivial_input
self._target_worker = target_worker
@@ -247,6 +255,7 @@ class DynamicDrafter:
self._verify_scores = _HostCopy(need + 1)
self._have_lagged = False
self._pending: Optional[Prelaunch] = None
+ self._drafted_row: Optional[torch.Tensor] = None # batch row of each request slot in a prelaunched draft
self._bonus: Optional[torch.Tensor] = None
self._slot_offsets = torch.arange(max(widths(1)), dtype=torch.int64, device=device)
runner = target_worker.model_runner
@@ -267,6 +276,33 @@ class DynamicDrafter:
self._sampled_depth = tree.shape.max_depth
# ----------------------------------------------------------------- policy
+ def warm_up(self, batch_sizes: Sequence[int]) -> None:
+ """Compile, before serving, the round tail's Triton kernels at every shape a round can take: the node
+ ranking at each tree depth, the verify selection and the batch-size-1 tail-mask words at each verify width
+ of ``batch_sizes``. Their shapes are compile-time constants, so a first use inside a served round compiles
+ there (hundreds of milliseconds on a cold kernel cache) and stalls every request of the batch."""
+ tree = self.tree
+ if not tree.scores.is_cuda:
+ return
+
+ widths = sorted({w for bs in batch_sizes for w in self._widths(bs)})
+ widest = max(widths)
+ for depth in range(1, tree.shape.max_depth + 1):
+ count = min(tree.shape.num_nodes(depth), widest - 1)
+ ranked, _ = tree.rank(1, depth, count)
+ for width in widths:
+ if 1 < width <= count + 1:
+ tree.select(1, min(depth, width - 1), ranked, width)
+ graphs = self._algorithm.target_verify_graphs
+ if graphs is not None and graphs.tail_mask is not None:
+ from eagle_harness.kernels.verify_prep import MAX_TAIL_WIDTH, tree_tail_words
+
+ committed = torch.zeros(1, dtype=torch.int64, device=tree.scores.device) # the staged seq_lens' dtype
+ for width in self._widths(1):
+ if 1 < width <= MAX_TAIL_WIDTH:
+ mask = torch.zeros(width * width, dtype=torch.bool, device=tree.scores.device)
+ tree_tail_words(mask, committed, torch.empty(width, dtype=torch.int64, device=mask.device), width)
+
@property
def seeding(self) -> bool:
"""Whether the last drafted round was forced to seed the live costs of its batch bucket."""
@@ -284,34 +320,59 @@ class DynamicDrafter:
if self.live is None:
return self.cost
bucket = self._bucket(bs)
- if self.live.ready(bucket) and bucket in self.cost.tables and bucket not in self._unpriced:
+ if not self._seeds(bucket) and bucket in self.cost.tables and bucket not in self._unpriced:
return self.cost
self.fixed.force_width = self.live.seed_width(bucket)
return self.fixed
+ def _seeds(self, bucket: int) -> bool:
+ """Whether a round at ``bucket`` belongs to its seed sweep: the bucket is not ready, and either no ready
+ buckets around it price it (:meth:`LiveCosts.priced`) or the load has dwelt there long enough
+ (:data:`LIVE_SEED_AFTER_ROUNDS`) to pay for measuring it."""
+ return not self.live.ready(bucket) and (
+ not self.live.priced(bucket) or self._visits[bucket] > LIVE_SEED_AFTER_ROUNDS
+ )
+
+ @property
+ def round_timer(self) -> Optional[RoundTimer]:
+ """The timer of this round's verify span; None for a round priced from neighbouring buckets (only ready
+ buckets and seed sweeps record, so the ready buckets change on the same round on every TP rank)."""
+ return None if self._interpolated else self.timer
+
def _begin_round(self, batch: "ScheduleBatch") -> None:
"""Read the last rounds' timings; refresh (and share) the live tables on the refresh rounds."""
if self.live is None:
return
bs = len(batch.reqs)
bucket = self._bucket(bs)
- seeding = not self.live.ready(bucket)
+ self._visits[bucket] += 1
+ seeding = self._seeds(bucket)
self.timer.drain(wait=seeding)
self._rounds += 1
ready = self.live.ready(bucket)
+ interpolated = not ready and not self._seeds(bucket)
# Table refreshes happen on the same rounds on every TP rank (round count and seed state agree), from
# rank 0's cells, so the ranks' decisions agree.
- if (ready and (seeding or self._rounds == 1)) or self._rounds % LIVE_REFRESH_ROUNDS == 0:
+ newly_priced = interpolated and bucket not in self.cost.tables
+ if (ready and (seeding or self._rounds == 1)) or newly_priced or self._rounds % LIVE_REFRESH_ROUNDS == 0:
if self._sync_cells is not None:
self.live.cells = self._sync_cells(self.live.cells)
- self.cost.set_tables(self.live.tables())
+ # Every bucket served so far keeps its table, interpolated ones included (they have no cells).
+ self.cost.set_tables(self.live.tables(also=tuple(self._visits)))
for measured_bucket in self.cost.tables:
self._check_priced(measured_bucket)
if self._save_cells is not None and (seeding or self._rounds % (LIVE_REFRESH_ROUNDS * LIVE_SAVE_REFRESHES) == 0):
self._save_cells()
- if seeding:
+ if seeding and ready:
logger.info("eagle-harness: live costs seeded for batch bucket %d: %s", bucket, self._table_summary(bucket))
- self._seeding = None if ready else (bucket, self.average_context(batch))
+ elif newly_priced:
+ logger.info(
+ "eagle-harness: live costs of batch bucket %d priced from the buckets around it: %s",
+ bucket,
+ self._table_summary(bucket),
+ )
+ self._interpolated = interpolated
+ self._seeding = None if ready or interpolated else (bucket, self.average_context(batch))
def _check_priced(self, bucket: int) -> None:
"""Keep the fixed shape at a bucket whose measured costs the cost model refuses (its ratio sanity checks)."""
@@ -334,7 +395,9 @@ class DynamicDrafter:
)
def _sample_steps(self) -> bool:
- return self.live is not None and (self._seeding is not None or self._rounds % LIVE_REFRESH_ROUNDS == 0)
+ return self.live is not None and (
+ self._seeding is not None or (self._rounds % LIVE_REFRESH_ROUNDS == 0 and not self._interpolated)
+ )
def _timed_steps(self, bs: int, run: Callable[[], int], context: int = 0) -> int:
"""Time seed steps and one queued draft prefix per refresh period, on its executing stream."""
@@ -397,6 +460,23 @@ class DynamicDrafter:
torch.cuda.current_stream().wait_stream(pending.stream)
return pending
+ def _keep_drafted(self, pending: Prelaunch, batch: "ScheduleBatch") -> bool:
+ """Whether ``pending`` drafted ``batch``: the batch it was queued for, or that batch less the requests the
+ scheduler dropped since (finished ones), whose rows the tree and the staged batch then keep. At large batch
+ sizes some request finishes nearly every round, so without the second case each round drafted twice."""
+ key = batch_key(batch)
+ if pending.key == key:
+ return True
+ if not set(key) <= set(pending.key):
+ return False
+ drafted = len(pending.key) # the staged batch is still the one the prelaunch drafted
+ if self._drafted_row is None:
+ self._drafted_row = torch.zeros(self.steps.req_to_token.shape[0], dtype=torch.int64, device=self._device)
+ self._drafted_row[self.steps.req_pool_indices[:drafted]] = torch.arange(drafted, device=self._device)
+ self.tree.keep_rows(self._drafted_row[batch.req_pool_indices])
+ self.steps.load_batch(len(key), batch.seq_lens, batch.req_pool_indices)
+ return True
+
# ------------------------------------------------------------------ round
def draft(self, batch: "ScheduleBatch") -> "EagleVerifyInput":
"""Grow this round's tree and return the verify input (a trivial one when no tree is drafted)."""
@@ -409,7 +489,7 @@ class DynamicDrafter:
self._begin_round(batch)
policy = self.policy(bs)
context = self.average_context(batch)
- if pending is not None and pending.key == batch_key(batch):
+ if pending is not None and self._keep_drafted(pending, batch):
depth = pending.next_depth
else:
self.steps.load_batch(bs, batch.seq_lens, batch.req_pool_indices)
@@ -464,6 +544,7 @@ class DynamicDrafter:
width = pending.width
else:
width = self._chain_width(bs)
+ if pending is None or pending.width != width or not self._keep_drafted(pending, batch):
# Staged at every width: the draft extend after the verify reads the batch from the steps.
self.steps.load_batch(bs, batch.seq_lens, batch.req_pool_indices)
if width > 1:
diff --git a/eagle_harness/sglang/plain_decode.py b/eagle_harness/sglang/plain_decode.py
index bc35489..037233a 100644
--- a/eagle_harness/sglang/plain_decode.py
+++ b/eagle_harness/sglang/plain_decode.py
@@ -114,6 +114,8 @@ class NativeDecode:
self._requests = NoSpecRequests() if enabled else None
self._track_mamba = track_mamba
self._verify_limit = verify_limit # larger batches decode natively
+ if enabled:
+ warm_up(getattr(req_to_token, "device", None))
# The running batch the next prefill's requests join: the last decode's rows plus the requests prefilled since.
self._decoding: tuple = ()
self._since = 0
@@ -159,6 +161,20 @@ class NativeDecode:
return plain_decode(batch, self._target_worker, self._req_to_token, track_mamba=self._track_mamba)
+def warm_up(device: Optional[torch.device]) -> None:
+ """Build, before serving, the engine kernel that only native decode uses in a speculative server: the decode
+ positions (``clamp_position`` on the int64 sequence lengths, a JIT module that nvcc builds in about 3 s). A server
+ otherwise builds it at its first native round, mid-serving, where the build stalls every running request and the
+ served policy's measurement of native decode."""
+ if device is None or device.type != "cuda":
+ return
+ try:
+ from sglang.kernels.ops.attention.clamp_position import clamp_position
+ except ImportError: # an engine without the JIT module computes the positions in torch
+ return
+ clamp_position(torch.ones(1, dtype=torch.int64, device=device))
+
+
def plain_decode(
batch: "ScheduleBatch", target_worker: "TpModelWorker", req_to_token: torch.Tensor, *, track_mamba: bool = False
) -> "GenerationBatchResult":
diff --git a/eagle_harness/sglang/row_attention.py b/eagle_harness/sglang/row_attention.py
index 1427d53..2023be5 100644
--- a/eagle_harness/sglang/row_attention.py
+++ b/eagle_harness/sglang/row_attention.py
@@ -29,23 +29,25 @@ from eagle_harness.kernels.row_attention import RowsLaunch, rows_attention, rows
# Per mode, the fastest of a sweep at the TP4 draft shapes on B300 (10 heads x 128, 148 SMs, window 4096, bs 1,
# contexts 1k-4k; attention + merge in a CUDA graph with a cold L2); neighbouring split counts are within ~10%.
-# The sweep's winners put 4 waves of (head, split) programs on the SMs for a step (64 splits) and 1.5 for the extend
-# (24); other GPUs and TP sizes keep those waves (draft_launches). Fixed per server, not autotuned, so the merge
-# order of the splits, and so the outputs, stay the same run to run.
+# The sweep's winners put 4 waves of (request, head, split) programs on the SMs for a step (64 splits) and 1.5 for
+# the extend (24); other GPUs, TP sizes and batch sizes keep those waves (draft_launches). Fixed per captured batch
+# size, not autotuned, so the merge order of the splits, and so the outputs, stay the same run to run.
STEP_WAVES, EXTEND_WAVES = 4.0, 1.5
STEP_LAUNCH = RowsLaunch(splits=64, block_n=64) # a draft step's top-K rows, at the reference shape
EXTEND_LAUNCH = RowsLaunch(splits=24, block_n=128) # the draft extend's causal rows, at the reference shape
MAX_SPLITS = max(STEP_LAUNCH.splits, EXTEND_LAUNCH.splits)
-def draft_launches(heads: int, device: torch.device) -> Tuple[RowsLaunch, RowsLaunch]:
- """The (step, extend) launches for ``heads`` draft heads per rank on ``device``: the key splits that keep the
- reference sweep's program waves (a step's splits a power of two, the extend's a multiple of 8; at most 128)."""
+def draft_launches(programs: int, device: torch.device) -> Tuple[RowsLaunch, RowsLaunch]:
+ """The (step, extend) launches for ``programs`` (request, head) programs per key split (batch size x draft heads
+ per rank) on ``device``: the key splits that keep the reference sweep's program waves (a step's splits a power of
+ two, the extend's a multiple of 8, below 8 a power of two; at most 128)."""
if device.type != "cuda":
return STEP_LAUNCH, EXTEND_LAUNCH
sms = torch.cuda.get_device_properties(device).multi_processor_count
- step = min(triton.next_power_of_2(triton.cdiv(int(STEP_WAVES * sms), heads)), 128)
- extend = min(triton.cdiv(triton.cdiv(int(EXTEND_WAVES * sms), heads), 8) * 8, 128)
+ step = min(triton.next_power_of_2(triton.cdiv(int(STEP_WAVES * sms), programs)), 128)
+ extend = triton.cdiv(int(EXTEND_WAVES * sms), programs)
+ extend = min(triton.next_power_of_2(extend), triton.cdiv(extend, 8) * 8, 128)
return RowsLaunch(splits=step, block_n=STEP_LAUNCH.block_n), RowsLaunch(splits=extend, block_n=EXTEND_LAUNCH.block_n)
@@ -113,8 +115,9 @@ class DraftRowAttention(AttentionBackend):
config = draft_runner.model_config
self.num_heads = config.num_attention_heads // get_parallel().attn_tp_size
self.head_dim = config.head_dim
- self.step_launch, self.extend_launch = draft_launches(self.num_heads, device)
- splits = max(self.step_launch.splits, self.extend_launch.splits)
+ self._device = device
+ # The splits shrink as the batch grows (draft_launches); a batch of one has the most per request.
+ splits = max(launch.splits for launch in draft_launches(self.num_heads, device))
parts = max_bs * self.num_heads * (splits + 1) * rows_padded(max_rows_per_request)
self.part_out = torch.empty(parts, self.head_dim, dtype=torch.float32, device=device)
self.part_lse = torch.empty(parts, dtype=torch.float32, device=device)
@@ -199,6 +202,7 @@ class DraftRowAttention(AttentionBackend):
q = q.view(rows, self.num_heads, self.head_dim)
out = torch.empty_like(q)
rows_per_request, step, seq_lens, req_pool_indices, ancestors = self._group
+ step_launch, extend_launch = draft_launches(rows // rows_per_request * self.num_heads, self._device)
rows_attention(
q,
self.token_to_kv_pool.get_key_buffer(layer.layer_id),
@@ -213,7 +217,7 @@ class DraftRowAttention(AttentionBackend):
step=step,
window=self.window,
scale=layer.scaling,
- launch=self.extend_launch if step == 0 else self.step_launch,
+ launch=extend_launch if step == 0 else step_launch,
table_rows=req_pool_indices,
)
return out.view(rows, self.num_heads * self.head_dim)
diff --git a/eagle_harness/sglang/sampled_tree.py b/eagle_harness/sglang/sampled_tree.py
index 78547b9..474273c 100644
--- a/eagle_harness/sglang/sampled_tree.py
+++ b/eagle_harness/sglang/sampled_tree.py
@@ -6,7 +6,6 @@ import torch
from eagle_harness.kernels.sampled_draw import sample_children
-
class SampledTree:
"""Static proposal storage; node ids remain the ordinary DraftTree ids.
@@ -33,6 +32,8 @@ class SampledTree:
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)
+ # Per store row: 1/temperature, top-k, top-p, min-p of the request (identity until set_sampling writes it).
+ self.filters = torch.tensor([1.0, float(1 << 30), 1.0, 0.0], device=device).repeat(rows, 1)
self.seed = int(seed)
self.round = torch.zeros(1, dtype=torch.int32, device=device)
self.active = False
@@ -60,7 +61,21 @@ class SampledTree:
start=self.tree.shape.layer_start(step + 1),
rows_per_req=rows,
req_index=self.req_index[:bs],
+ filters=self.filters,
+ )
+
+ def set_sampling(self, req_pool_indices: torch.Tensor, sampling_info) -> None:
+ """Record each request's sampling settings at its pool slot, so its proposals follow the target's sampler."""
+ settings = torch.stack(
+ (
+ 1.0 / sampling_info.temperatures.view(-1).float(),
+ sampling_info.top_ks.float(),
+ sampling_info.top_ps.float(),
+ sampling_info.min_ps.float(),
+ ),
+ dim=1,
)
+ self.filters.index_copy_(0, req_pool_indices.to(device=self.filters.device, dtype=torch.int64), settings)
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."""
diff --git a/eagle_harness/sglang/verify_tail.py b/eagle_harness/sglang/verify_tail.py
index c3095f2..88fae69 100644
--- a/eagle_harness/sglang/verify_tail.py
+++ b/eagle_harness/sglang/verify_tail.py
@@ -12,12 +12,20 @@ graph per ``(batch size, depth)`` for the ranking and one per ``(batch size,
depth, width)`` for the selection and the build replay them with a launch
each. When the width is known before the ranking (the cost model reads the
previous round's scores), :meth:`VerifyTail.ranked_verify_input` replays the
-ranking, the hand-off of its scores and the build as one graph. A graph is
-captured the first time its key occurs.
+ranking, the hand-off of its scores and the build as one graph.
+
+A key runs eagerly until it has occurred :data:`CAPTURE_AFTER` times, then is
+captured. A capture records and instantiates the whole tail and keeps its
+outputs in the graph pool: the host time of many eager tails, with the GPU
+waiting on the scheduler. Capturing a key at first sight paid that for every
+batch size a large batch passes through as it drains, most of which never
+recur. Waiting until the eager runs have cost about one capture (rent or buy)
+bounds the host time of a key at twice the better of the two.
"""
from __future__ import annotations
+from collections import Counter
from typing import Callable, Dict, NamedTuple, Tuple
import torch
@@ -38,57 +46,72 @@ class Ranking(NamedTuple):
scores: torch.Tensor # [count + 1] cumulative verify scores (root first), batch mean
+# Eager runs of a key before it is captured (see the module docstring).
+CAPTURE_AFTER = 16
+
+
def _capture(body: Callable[[], object]):
- """Run ``body`` once eagerly (Triton compiles), then capture it; returns ``(graph, outputs)``."""
- body()
+ """Capture ``body`` (its kernels are compiled: it has run eagerly); returns ``(graph, outputs)``."""
return capture(body)
+class _Graphs:
+ """``body()`` per key: eager for the key's first :data:`CAPTURE_AFTER` runs, then from its captured graph."""
+
+ def __init__(self) -> None:
+ self.graphs: Dict[Tuple, Tuple[torch.cuda.CUDAGraph, object]] = {}
+ self._runs: Counter = Counter()
+
+ def run(self, key: Tuple, body: Callable[[], object], static: bool = True):
+ """``static=False``: ``body`` reads tensors other than the ones a graph would replay, so it runs eagerly."""
+ if not static:
+ return body()
+ if key not in self.graphs:
+ self._runs[key] += 1
+ if self._runs[key] <= CAPTURE_AFTER:
+ return body()
+ self.graphs[key] = _capture(body)
+ graph, outputs = self.graphs[key]
+ graph.replay()
+ return outputs
+
+
class VerifyTail:
"""Graph-replayed ranking and verify-input build of a drafted tree."""
def __init__(self, tree: DraftTree, build_input: BuildInput):
self.tree = tree
self._build_input = build_input
- self._rankings: Dict[Tuple[int, int], Tuple[torch.cuda.CUDAGraph, Ranking]] = {}
- self._inputs: Dict[Tuple[int, int, int], Tuple[torch.cuda.CUDAGraph, EagleVerifyInput]] = {}
- self._ranked_inputs: Dict[Tuple[int, int, int, int], Tuple[torch.cuda.CUDAGraph, EagleVerifyInput]] = {}
+ self._rankings = _Graphs()
+ self._inputs = _Graphs()
+ self._ranked_inputs = _Graphs()
def rank(self, bs: int, depth: int, count: int) -> Ranking:
"""The best ``count`` nodes of the ``depth``-level tree and the cumulative scores of their prefixes."""
- key = (bs, depth)
- if key not in self._rankings:
- self._rankings[key] = _capture(lambda: self._rank(bs, depth, count))
- graph, ranking = self._rankings[key]
- graph.replay()
- return ranking
+ return self._rankings.run((bs, depth), lambda: self._rank(bs, depth, count))
def verify_input(self, bs: int, depth: int, width: int, ranking: Ranking) -> EagleVerifyInput:
"""sglang's verify input of the best ``width - 1`` ranked nodes plus the root."""
- key = (bs, depth, width)
- if key not in self._inputs:
- self._inputs[key] = _capture(lambda: self._select(bs, depth, width, ranking))
- graph, verify_input = self._inputs[key]
- graph.replay()
- return verify_input
+ # A graph reads the tensors it was captured with: only the ranking graph's own outputs stay current.
+ ranked = self._rankings.graphs.get((bs, depth))
+ return self._inputs.run(
+ (bs, depth, width),
+ lambda: self._select(bs, depth, width, ranking),
+ static=ranked is not None and ranked[1] is ranking,
+ )
def ranked_verify_input(
self, bs: int, depth: int, count: int, width: int, on_rank: Callable[[Ranking], None]
) -> EagleVerifyInput:
""":meth:`rank`, ``on_rank(ranking)`` (device work, e.g. copying the scores out) and
:meth:`verify_input` in one graph replay."""
- key = (bs, depth, count, width)
- if key not in self._ranked_inputs:
- def body() -> EagleVerifyInput:
- ranking = self._rank(bs, depth, count)
- on_rank(ranking)
- return self._select(bs, depth, width, ranking)
+ def body() -> EagleVerifyInput:
+ ranking = self._rank(bs, depth, count)
+ on_rank(ranking)
+ return self._select(bs, depth, width, ranking)
- self._ranked_inputs[key] = _capture(body)
- graph, verify_input = self._ranked_inputs[key]
- graph.replay()
- return verify_input
+ return self._ranked_inputs.run((bs, depth, count, width), body)
def _rank(self, bs: int, depth: int, count: int) -> Ranking:
ranked, scores = self.tree.rank(bs, depth, count)
diff --git a/eagle_harness/sglang/worker.py b/eagle_harness/sglang/worker.py
index 44da252..819ac7b 100644
--- a/eagle_harness/sglang/worker.py
+++ b/eagle_harness/sglang/worker.py
@@ -454,6 +454,7 @@ class EagleHarnessWorker(EAGLEWorkerV2):
else None
),
)
+ self._drafter.warm_up(capture_bs)
self._native_decode = NativeDecode(
self.target_worker,
self.req_to_token_pool.req_to_token,
@@ -531,6 +532,7 @@ class EagleHarnessWorker(EAGLEWorkerV2):
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)
+ sampled.set_sampling(batch.req_pool_indices, batch.sampling_info)
return self._prefill(batch, on_publish, grammar_barrier, pp_proxy_tensors)
native_decode = self._native_decode.select(batch)
if native_decode:
@@ -567,6 +569,7 @@ class EagleHarnessWorker(EAGLEWorkerV2):
else:
with self._draft_context(), spec_stage_span("draft"):
batch.spec_info = self._drafter.draft(batch)
+ timer = self._drafter.round_timer
width = self._drafter.last_width
rounds.round_start(len(batch.seq_lens), width, batch, settled=not self._drafter.seeding)
with spec_stage_span("verify"):
diff --git a/tests/test_draft_tree.py b/tests/test_draft_tree.py
index 7f432a9..65a5c8a 100644
--- a/tests/test_draft_tree.py
+++ b/tests/test_draft_tree.py
@@ -89,6 +89,33 @@ def test_frontier_hidden_and_ancestors_follow_parents():
assert torch.equal(tree.front_tokens[:K], ids.view(-1)[pick])
+def _grow(bs, root_p, root_ids, root_h, rounds, max_bs=None):
+ tree = DraftTree(TreeShape(K, DEPTH), max_bs or bs, H, torch.float32, torch.device("cpu"), max_verify=32)
+ _begin(tree, bs, root_p, root_ids, root_h)
+ for step, (p, ids, hidden) in enumerate(rounds, start=1):
+ tree.set_step_slots(bs, step, torch.arange(bs * K).view(bs, K) + 100 * step)
+ tree.step(bs, step, p, ids, hidden)
+ return tree
+
+
+def test_kept_rows_are_the_tree_of_the_kept_requests():
+ """A tree grown for 4 requests, compacted to requests 3, 0 and 2, equals the tree grown for those 3 alone."""
+ bs, keep = 4, torch.tensor([3, 0, 2])
+ root_p, root_ids, root_h, rounds = _random_round(bs, 3, seed=5)
+ tree = _grow(bs, root_p, root_ids, root_h, rounds)
+ tree.keep_rows(keep)
+ nodes = (keep[:, None] * K + torch.arange(K)).reshape(-1) # the kept requests' frontier rows
+ kept_rounds = [(p[nodes], ids[nodes], hidden[nodes]) for p, ids, hidden in rounds]
+ alone = _grow(3, root_p[keep], root_ids[keep], root_h[keep], kept_rounds, max_bs=bs)
+ for name in ("root_probs", "root_tokens", "root_hidden", "scores", "tokens", "parents", "front_scores",
+ "best", "best_prev", "layer_top", "delta_rows"):
+ assert torch.equal(getattr(tree, name)[:3], getattr(alone, name)[:3]), name
+ assert torch.equal(tree.front_tokens[: 3 * K], alone.front_tokens[: 3 * K])
+ assert torch.equal(tree.front_hidden[: 3 * K], alone.front_hidden[: 3 * K])
+ first = _grow(bs, root_p, root_ids, root_h, rounds)
+ assert torch.equal(tree.ancestors[:3], first.ancestors[keep])
+
+
def _fork_work_deltas(work_scores, node_count, top_k, verify_num):
"""calculate_work_deltas_kernel, one row."""
out = []
diff --git a/tests/test_drafter.py b/tests/test_drafter.py
index 0e358bb..794d62d 100644
--- a/tests/test_drafter.py
+++ b/tests/test_drafter.py
@@ -3,6 +3,7 @@
"""DynamicDrafter wiring checks that run on CPU (the round itself needs CUDA graphs)."""
+import collections
from types import SimpleNamespace
import pytest
@@ -106,6 +107,7 @@ def _sequenced(tiny: bool, stop: int, policy=None):
drafter.steps, drafter.tree, drafter.cost = steps, tree, _StopAt(cost, stop)
drafter.fixed = FixedShapePolicy(ComputeIntensity.HIGH, K, DEPTH, WIDTH)
drafter.live, drafter.timer, drafter._seeding = None, None, None
+ drafter._interpolated, drafter._visits = False, collections.Counter()
drafter._deltas_ready, drafter._deltas_slot = _Event(), 0
drafter._policy = drafter.fixed if policy == "fixed" else drafter.cost
drafter.policy = lambda bs: drafter._policy
@@ -202,6 +204,7 @@ def _chain_sequenced(stop: int):
drafter = DynamicDrafter.__new__(DynamicDrafter)
drafter.steps, drafter.tree, drafter.cost = steps, tree, cost
drafter.live, drafter.timer, drafter._seeding = None, None, None
+ drafter._interpolated, drafter._visits = False, collections.Counter()
drafter._deltas_ready, drafter._deltas_slot = _Event(), 0
drafter.policy = lambda bs: cost
return drafter, steps, policy
@@ -369,6 +372,53 @@ def test_prelaunched_chain_keeps_the_width_it_was_queued_with():
assert drafter.tail.built[-1] == (3, 1, 1, 2)
+class _KeptTree:
+ def __init__(self):
+ self.kept = []
+
+ def keep_rows(self, rows):
+ self.kept.append(rows.tolist())
+
+
+def _prelaunched_chain(width, drafted, plan):
+ """A chain drafter whose last round drafted the requests ``drafted`` (block-table rows) at ``width``."""
+ from eagle_harness.sglang.drafter import Prelaunch
+
+ drafter = _chain_drafter(plan)
+ drafter.tree, drafter._drafted_row = _KeptTree(), None
+ drafter.steps.req_to_token = torch.zeros(8, 4)
+ drafter.steps.req_pool_indices = torch.zeros(8, dtype=torch.int64)
+ drafter.steps.req_pool_indices[: len(drafted)] = torch.tensor(drafted)
+ pending = Prelaunch(tuple(drafted), drafter._queue_chain(len(drafted), width), width, stream=None)
+ drafter._take_pending = lambda: pending
+ return drafter
+
+
+def _requests(rows):
+ batch = _chain_batch(len(rows))
+ batch.req_pool_indices = torch.tensor(rows)
+ batch.reqs = [SimpleNamespace(kv=SimpleNamespace(req_pool_idx=r)) for r in rows]
+ return batch
+
+
+def test_a_batch_that_lost_requests_keeps_their_prelaunched_chain():
+ """Requests 1 and 4 finished after the prelaunch drafted [5, 1, 7, 4]: the round verifies the kept rows' draft
+ (batch positions 0 and 2) instead of drafting the chain again."""
+ drafter = _prelaunched_chain(4, [5, 1, 7, 4], plan=[4])
+ drafter.draft(_requests([5, 7]))
+ assert drafter.steps.ran == [1, 2] and drafter.steps.begun == [] # the prelaunch's steps only
+ assert drafter.tree.kept == [[0, 2]] and drafter.steps.loaded == [2]
+ assert drafter.tail.built == [(2, 3, 3, 4)]
+
+
[email protected]("rows, plan", [([5, 9], [4]), ([5, 7], [2])])
+def test_a_new_request_or_width_drafts_the_chain_again(rows, plan):
+ """A request the prelaunch did not draft (9), or a new width for the smaller batch, drafts from the begin."""
+ drafter = _prelaunched_chain(4, [5, 1, 7, 4], plan=plan)
+ drafter.draft(_requests(rows))
+ assert drafter.tree.kept == [] and drafter.steps.begun == [2]
+
+
@pytest.mark.parametrize("cycles, offset, sampled", [(1, -1, False), (1, 0, True), (1, 1, False), (2, 0, True)])
def test_live_draft_costs_continue_sampling_after_seeding(cycles, offset, sampled):
from eagle_harness.core.live_costs import LiveCosts
@@ -442,3 +492,104 @@ def test_average_context_reads_request_lengths_when_the_overlap_scheduler_drops_
assert DynamicDrafter.average_context(overlap) == 15
synchronous = SimpleNamespace(reqs=reqs, seq_lens=torch.tensor([10, 21]), seq_lens_cpu=torch.tensor([12, 22]))
assert DynamicDrafter.average_context(synchronous) == 17
+
+
+def _live_drafter(seeded):
+ """A drafter on the production policy with live costs whose ``seeded`` buckets are ready."""
+ from eagle_harness.core.live_costs import DRAFT_WIDTH, LiveCosts
+
+ drafter, _ = _sequenced(True, stop=0)
+ del drafter.policy
+ drafter.cost = _cost()
+ drafter.live = LiveCosts(widths=lambda bs: [1, 8, 16], seed_samples=1)
+ for bucket in seeded:
+ for width, us in ((1, 4000.0 + 50 * bucket), (8, 4300.0 + 80 * bucket), (16, 4600.0 + 100 * bucket)):
+ drafter.live.record(bucket, width, 100, us)
+ drafter.live.record(bucket, DRAFT_WIDTH, 100, 170.0)
+ drafter.cost.set_tables(drafter.live.tables())
+ drafter._bucket = lambda bs: bs
+ drafter.timer = SimpleNamespace(drain=lambda **kw: None)
+ drafter._sync_cells = drafter._save_cells = None
+ drafter._unpriced = set()
+ drafter._rounds = 1
+ return drafter
+
+
+def test_a_bucket_between_seeded_buckets_serves_the_cost_model_without_a_seed_sweep():
+ """A draining batch passes through sizes the load never dwells in: they are priced from the buckets around
+ them, their rounds are not timed (so readiness changes only on seed rounds, alike on every TP rank), and only a
+ bucket the load stays in for LIVE_SEED_AFTER_ROUNDS rounds is seeded itself."""
+ from eagle_harness.sglang.drafter import LIVE_SEED_AFTER_ROUNDS
+
+ drafter = _live_drafter(seeded=(1, 8))
+ batch = SimpleNamespace(reqs=[None] * 4, seq_lens_cpu=torch.tensor([100] * 4))
+ drafter._begin_round(batch)
+ assert 4 in drafter.cost.tables and drafter.policy(4) is drafter.cost
+ assert drafter._seeding is None and drafter.round_timer is None
+ tables = drafter.cost.tables
+ drafter._begin_round(SimpleNamespace(reqs=[None] * 6, seq_lens_cpu=torch.tensor([100] * 6)))
+ assert drafter.cost.tables is not tables and {4, 6} <= set(drafter.cost.tables) # 6 joins, 4 stays
+ tables = drafter.cost.tables
+ drafter._begin_round(batch)
+ assert drafter.cost.tables is tables # bucket 4 is still tabled: no refresh (and no TP broadcast)
+ for _ in range(LIVE_SEED_AFTER_ROUNDS):
+ drafter._begin_round(batch)
+ assert drafter.policy(4) is drafter.fixed and drafter.fixed.force_width == 1
+ assert drafter._seeding == (4, 100) and drafter.round_timer is drafter.timer
+
+
+def test_a_bucket_outside_the_seeded_ones_is_seeded_on_its_first_round():
+ drafter = _live_drafter(seeded=(1, 8))
+ drafter._begin_round(SimpleNamespace(reqs=[None] * 12, seq_lens_cpu=torch.tensor([100] * 12)))
+ assert 12 not in drafter.cost.tables and drafter.policy(12) is drafter.fixed
+ assert drafter._seeding == (12, 100) and drafter.round_timer is drafter.timer
+
+
+def test_the_round_timer_waits_for_spans_of_unready_buckets():
+ """Seed samples land on the same round on every TP rank: readiness decides which buckets are interpolated."""
+ from eagle_harness.core.live_costs import DRAFT_WIDTH, LiveCosts
+ from eagle_harness.sglang.drafter import RoundTimer
+
+ class Pending:
+ waited = False
+
+ def query(self):
+ return False
+
+ def synchronize(self):
+ self.waited = True
+
+ def elapsed_time(self, end):
+ return 4.0
+
+ live = LiveCosts(widths=lambda bs: [1], seed_samples=1)
+ live.record(1, 1, 100, 4000.0)
+ live.record(1, DRAFT_WIDTH, 100, 170.0)
+ timer = RoundTimer(live)
+ ready_end, unready_end = Pending(), Pending()
+ timer._pending = [(Pending(), ready_end, 1, 1, 100, 1), (Pending(), unready_end, 2, 1, 100, 1)]
+ timer.drain(wait=False)
+ assert not ready_end.waited and unready_end.waited
+ assert live.cells[(2, 1, 0)].samples == 1 and len(timer._pending) == 1
+
+
+def test_warm_up_runs_the_tail_kernels_at_every_depth_and_verify_width():
+ """Every ranking (one per depth) and selection (one per verify width) shape compiles before serving."""
+ drafter, _ = _sequenced(True, stop=0)
+ calls = []
+ shape = TreeShape(K, DEPTH)
+ drafter.tree = SimpleNamespace(
+ scores=SimpleNamespace(is_cuda=True),
+ shape=shape,
+ rank=lambda bs, depth, count: (calls.append(("rank", depth, count)) or "ranked", None),
+ select=lambda bs, depth, ranked, width: calls.append(("select", depth, width)),
+ )
+ drafter._widths = lambda bs: [16, 8, 1] if bs <= 8 else [16, 8, 4, 1]
+ drafter._algorithm = SimpleNamespace(target_verify_graphs=None)
+ drafter.warm_up([1, 8, 32])
+ ranks = [c for c in calls if c[0] == "rank"]
+ assert [c[1] for c in ranks] == list(range(1, DEPTH + 1))
+ assert all(count == min(shape.num_nodes(depth), 15) for _, depth, count in ranks)
+ assert {c[2] for c in calls if c[0] == "select"} == {4, 8, 16}
+ assert ("select", 1, 4) in calls and ("select", 3, 4) in calls # a depth-1 tree verifies at most K + 1 tokens
+ assert not any(c[0] == "select" and c[2] > shape.num_nodes(c[1]) + 1 for c in calls)
diff --git a/tests/test_live_costs.py b/tests/test_live_costs.py
index c38eb98..d9cd5cd 100644
--- a/tests/test_live_costs.py
+++ b/tests/test_live_costs.py
@@ -267,3 +267,49 @@ def test_offline_tables_are_validated_and_keyed_at_load(tmp_path):
with pytest.raises(ValueError, match="another setup"):
load_cost_tables(str(tmp_path / "cost"), CostKey("H100", 4, "qwen:abc", "eagle4:def", "sglang 0.5.23", "torch.bfloat16"))
assert load_cost_tables(str(tmp_path / "missing"), KEY) == {}
+
+
+def _bucketed(**kw) -> LiveCosts:
+ """Widths per bucket as captured: width 4 only from batch size 5 up."""
+ return LiveCosts(widths=lambda bs: [16, 8, 1] if bs <= 4 else [16, 8, 4, 1], key=KEY, seed_samples=2, **kw)
+
+
+def test_a_bucket_between_ready_buckets_is_priced_linearly_in_the_batch_size():
+ live = _bucketed()
+ _seed(live, 1, {1: 4000.0, 8: 4500.0, 16: 5000.0}, draft_us=150.0)
+ assert not live.priced(4) # one ready bucket: nothing on the other side
+ _seed(live, 8, {1: 4700.0, 4: 4900.0, 8: 5400.0, 16: 6400.0}, draft_us=220.0)
+ assert live.ready(1) and live.ready(8) and not live.ready(4)
+ assert live.priced(4) and live.priced(1) and not live.priced(12) # never extrapolated
+ assert live.verify_us(4, 1) == pytest.approx(4000.0 + 3 / 7 * 700.0)
+ assert 4 not in live.tables() and 12 not in live.tables(also=(12,))
+ table = live.tables(also=(4, 6))[4]
+ assert table.intervals[0].target.value == pytest.approx((4300.0, 4885.714, 5600.0), rel=1e-6)
+ assert table.intervals[0].draft.value == pytest.approx((180.0,))
+ # Width 4 (bucket 6) is linear between bucket 1's widths 1 and 8 before it is linear in the batch size.
+ below = 4000.0 + 3 / 7 * 500.0
+ width4 = live.tables(also=(6,))[6].intervals[0].target.value[1]
+ assert width4 == pytest.approx(below + 5 / 7 * (4900.0 - below))
+ assert live.verify_us(6, 4) == pytest.approx(width4)
+
+
+def test_an_interpolated_bucket_keeps_its_own_fully_sampled_cells():
+ live = _bucketed()
+ _seed(live, 1, {1: 4000.0, 8: 4500.0, 16: 5000.0})
+ _seed(live, 8, {1: 4700.0, 4: 4900.0, 8: 5400.0, 16: 6400.0})
+ live.record(4, 16, 500, 5200.0)
+ live.record(4, 16, 500, 5100.0)
+ assert not live.ready(4)
+ target = live.tables(also=(4,))[4].intervals[0].target.value
+ assert target[2] == 5100.0 and target[0] == pytest.approx(4000.0 + 3 / 7 * 700.0)
+
+
+def test_readiness_follows_a_replaced_cells_dict():
+ """A TP sync replaces the cells with rank 0's: the sample counts behind ready() are rebuilt from them."""
+ live, seeded = _bucketed(), _bucketed()
+ _seed(seeded, 1, {1: 4000.0, 8: 4500.0, 16: 5000.0})
+ assert not live.ready(1)
+ live.cells = seeded.cells
+ assert live.ready(1) and live.seed_width(1) is None
+ live.cells = {}
+ assert not live.ready(1) and live.seed_width(1) == 1
diff --git a/tests/test_plain_decode.py b/tests/test_plain_decode.py
index ed6a91e..25ab4d2 100644
--- a/tests/test_plain_decode.py
+++ b/tests/test_plain_decode.py
@@ -414,6 +414,28 @@ def test_batches_above_the_verify_limit_capture_only_the_native_decode_graph():
assert native.forward_mode is ForwardMode.DECODE
[email protected]("enabled", [True, False])
+def test_the_native_route_builds_its_decode_position_kernel_before_serving(monkeypatch, enabled):
+ """The engine computes native decode's positions with a JIT module (nvcc, about 3 s); a server with the native route
+ builds it at startup, not at its first native round mid-serving."""
+ pytest.importorskip("sglang")
+ import torch
+
+ from sglang.kernels.ops.attention import clamp_position as engine_positions
+
+ from eagle_harness.sglang import plain_decode as plain_module
+
+ built = []
+ monkeypatch.setattr(engine_positions, "clamp_position", lambda seq_lens: built.append(seq_lens.dtype))
+ monkeypatch.setattr(plain_module.torch, "ones", lambda *shape, dtype, device: torch.zeros(*shape, dtype=dtype))
+ on_gpu = SimpleNamespace(device=torch.device("cuda"))
+ plain_module.NativeDecode(None, on_gpu, None, enabled=enabled)
+ assert built == ([torch.int64] if enabled else [])
+ plain_module.NativeDecode(None, SimpleNamespace(device=torch.device("cpu")), None, enabled=enabled)
+ plain_module.NativeDecode(None, None, None, enabled=enabled)
+ assert built == ([torch.int64] if enabled else [])
+
+
def test_prefills_joining_a_batch_above_the_verify_limit_skip_the_draft_for_life():
pytest.importorskip("sglang")
from eagle_harness.sglang.plain_decode import NativeDecode
diff --git a/tests/test_prelaunch_gpu.py b/tests/test_prelaunch_gpu.py
index e31112b..fe3b125 100644
--- a/tests/test_prelaunch_gpu.py
+++ b/tests/test_prelaunch_gpu.py
@@ -40,6 +40,17 @@ def caller_stream(request):
stream.synchronize()
+def _prelaunch_drafter(chain_width):
+ drafter = DynamicDrafter.__new__(DynamicDrafter)
+ drafter._device = torch.device("cuda")
+ drafter.live = None
+ drafter._prelaunch_stream = None
+ drafter._pending = None
+ drafter._chain_width = (lambda bs: chain_width) if chain_width is not None else None
+ drafter.policy = lambda bs: None
+ return drafter
+
+
@pytest.mark.parametrize("consumer", ["filter", "merge_into", "merge_from"])
def test_prelaunch_roots_are_ready_for_scheduler_compaction(consumer, caller_stream, chain_width):
pending = EagleDraftInput(
@@ -59,11 +70,8 @@ def test_prelaunch_roots_are_ready_for_scheduler_compaction(consumer, caller_str
reqs=[SimpleNamespace(kv=SimpleNamespace(req_pool_idx=i)) for i in range(2)],
req_pool_indices=torch.arange(2, device="cuda"),
)
- drafter = DynamicDrafter.__new__(DynamicDrafter)
- drafter._prelaunch_stream = None
- drafter._pending = None
- drafter._chain_width = (lambda bs: chain_width) if chain_width is not None else None
- drafter._queue_until_decision = lambda bs: 1
+ drafter = _prelaunch_drafter(chain_width)
+ drafter._queue_until_decision = lambda bs, policy, context=0: 1
drafter._queue_chain = lambda bs, width: max(0, width - 1)
def compact():
@@ -110,10 +118,7 @@ def test_prelaunch_finishes_reading_slots_before_scheduler_reuses_them(caller_st
reqs=[SimpleNamespace(kv=SimpleNamespace(req_pool_idx=i)) for i in range(2)],
req_pool_indices=torch.arange(2, device="cuda"),
)
- drafter = DynamicDrafter.__new__(DynamicDrafter)
- drafter._prelaunch_stream = None
- drafter._pending = None
- drafter._chain_width = (lambda bs: chain_width) if chain_width is not None else None
+ drafter = _prelaunch_drafter(chain_width)
def queue_steps(bs):
# A fence after extend alone is too early: draft steps still read slot mappings.
@@ -121,7 +126,7 @@ def test_prelaunch_finishes_reading_slots_before_scheduler_reuses_them(caller_st
observed.copy_(slots)
return 1
- drafter._queue_until_decision = queue_steps
+ drafter._queue_until_decision = lambda bs, policy, context=0: queue_steps(bs)
drafter._queue_chain = lambda bs, width: queue_steps(bs)
torch.cuda.synchronize()
done = drafter.prelaunch(batch, extend=lambda: None, inputs=(slots,))
@@ -144,10 +149,7 @@ def test_scheduler_result_copy_does_not_wait_for_prelaunch(caller_stream, chain_
accept_lens=torch.ones(1, dtype=torch.int32, device="cuda"),
copy_done=torch.cuda.Event(),
)
- drafter = DynamicDrafter.__new__(DynamicDrafter)
- drafter._prelaunch_stream = None
- drafter._pending = None
- drafter._chain_width = (lambda bs: chain_width) if chain_width is not None else None
+ drafter = _prelaunch_drafter(chain_width)
finished = torch.cuda.Event()
def queue_steps(bs):
@@ -155,7 +157,7 @@ def test_scheduler_result_copy_does_not_wait_for_prelaunch(caller_stream, chain_
finished.record()
return 1
- drafter._queue_until_decision = queue_steps
+ drafter._queue_until_decision = lambda bs, policy, context=0: queue_steps(bs)
drafter._queue_chain = lambda bs, width: queue_steps(bs)
torch.cuda.synchronize()
done = drafter.prelaunch(batch, extend=lambda: None, inputs=())
diff --git a/tests/test_sampled_draw_gpu.py b/tests/test_sampled_draw_gpu.py
index 07bc70c..5b6a68d 100644
--- a/tests/test_sampled_draw_gpu.py
+++ b/tests/test_sampled_draw_gpu.py
@@ -122,3 +122,64 @@ def test_stores_follow_the_request_slot_map():
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() == 0
+
+
+# (1/temperature, top-k, top-p, min-p): coding, narrow top-k, min-p, top-1, and narrow top-p.
+FILTER_CASES = [(1.0, 20, 0.95, 0.0), (2.0, 3, 1.0, 0.0), (1.0, 1 << 30, 1.0, 0.1),
+ (1.0, 1, 1.0, 0.0), (0.5, 1 << 30, 0.3, 0.0)]
+
+
[email protected]("inv_t, top_k, top_p, min_p", FILTER_CASES)
+def test_filtered_draw_matches_reference_on_filtered_logits(inv_t, top_k, top_p, min_p):
+ from eagle_harness.core.sampled_tree import filter_proposal_logits
+ from eagle_harness.kernels.sampled_draw import sample_children
+
+ bs, nc, k = 4, 128, 4
+ gen = torch.Generator().manual_seed(17 + top_k)
+ logits = torch.randn(bs, nc, generator=gen) * 3
+ token_ids = torch.stack([torch.randperm(5000, generator=gen)[:nc] for _ in range(bs)])
+ uniforms = torch.rand(bs, nc, generator=gen)
+ req = torch.tensor([6, 1, 3, 0])
+ filters = torch.tensor([1.0, float(1 << 30), 1.0, 0.0]).repeat(8, 1)
+ filters[req] = torch.tensor([inv_t, float(top_k), top_p, min_p])
+ rows = torch.ones(bs)
+ filtered = filter_proposal_logits(logits, rows / inv_t, rows * top_k, rows * top_p, rows * min_p)
+ kept = torch.isfinite(filtered).sum(dim=1)
+ reference = draw_children(filtered, token_ids, k, uniforms=uniforms)
+ q, ids, positions = _stores(8, 1, nc, k)
+ scores, tokens = sample_children(
+ logits.to(DEV), token_ids.to(DEV), k, seed=1, 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, uniforms=uniforms.to(DEV),
+ req_index=req.to(DEV), filters=filters.to(DEV),
+ )
+ if not INTERPRET:
+ torch.cuda.synchronize()
+ q, positions, scores, tokens = q.cpu(), positions.cpu(), scores.cpu(), tokens.cpu()
+ torch.testing.assert_close(q[req, 0], reference.probs, rtol=1e-5, atol=1e-7)
+ assert ((q[req, 0] > 0) == torch.isfinite(filtered)).all()
+ torch.testing.assert_close(scores, reference.scores, rtol=1e-5, atol=1e-7)
+ for b in range(bs):
+ live = min(k, int(kept[b])) # draws past the kept support are inert (q = 0) and need not match
+ torch.testing.assert_close(positions[req[b], :live], reference.positions[b, :live], rtol=0, atol=0)
+ torch.testing.assert_close(tokens[b, :live], reference.tokens[b, :live], rtol=0, atol=0)
+ assert positions[req[b]].unique().numel() == k # inert draws stay distinct candidates
+ assert (q[req[b], 0].gather(0, positions[req[b], live:]) == 0).all()
+
+
+def test_identity_filters_draw_bitwise_like_no_filters():
+ from eagle_harness.kernels.sampled_draw import sample_children
+
+ nc, k = 128, 4
+ gen = torch.Generator().manual_seed(5)
+ logits = (torch.randn(3, nc, generator=gen) * 2).to(DEV)
+ token_ids = torch.arange(nc).expand(3, -1).contiguous().to(DEV)
+ identity = torch.tensor([1.0, float(1 << 30), 1.0, 0.0]).repeat(3, 1).to(DEV)
+ out = []
+ for filters in (None, identity):
+ q, ids, positions = _stores(3, 1, nc, k)
+ scores, tokens = sample_children(logits, token_ids, k, seed=4, launch=2,
+ counter=torch.full((1,), 7, dtype=torch.int32, device=DEV), q=q, q_ids=ids,
+ positions=positions, slot=0, start=0, rows_per_req=1, filters=filters)
+ out.append((q.cpu(), positions.cpu(), scores.cpu(), tokens.cpu()))
+ for a, b in zip(*out):
+ torch.testing.assert_close(a, b, rtol=0, atol=0)
diff --git a/tests/test_sampled_tree.py b/tests/test_sampled_tree.py
index 28a994d..260e474 100644
--- a/tests/test_sampled_tree.py
+++ b/tests/test_sampled_tree.py
@@ -205,3 +205,46 @@ def test_token_dependent_descendants_do_not_bias_pruned_root_distribution(width)
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)
+
+
+def _keep_like_the_verify_filter(probs, top_k, top_p, min_p):
+ """The target's verify support, element by element: top-k and top-p of the unfiltered row, then min-p."""
+ keep = []
+ for i, p in enumerate(probs.tolist()):
+ higher = [j for j, x in enumerate(probs.tolist()) if x > p or (x == p and j < i)]
+ mass = sum(probs[j].item() for j in higher)
+ keep.append(len(higher) < top_k and mass < top_p and p >= min_p * probs.max().item())
+ return torch.tensor(keep)
+
+
[email protected]("temperature, top_k, top_p, min_p", [(1.0, 20, 0.95, 0.0), (0.7, 3, 1.0, 0.0),
+ (1.3, 1 << 30, 0.5, 0.0), (1.0, 1 << 30, 1.0, 0.2),
+ (1.0, 1, 1.0, 0.0)])
+def test_proposal_filter_keeps_the_target_sampler_support(temperature, top_k, top_p, min_p):
+ from eagle_harness.core.sampled_tree import filter_proposal_logits
+
+ gen = torch.Generator().manual_seed(top_k)
+ logits = torch.randn(3, 40, generator=gen) * 2
+ logits[0, 5] = logits[0, 9] = logits[0].max() + 1 # a tie at the top ranks by index
+ ones = torch.ones(3)
+ out = filter_proposal_logits(logits, ones * temperature, ones * top_k, ones * top_p, ones * min_p)
+ probs = torch.softmax(logits / temperature, dim=-1)
+ for row in range(3):
+ keep = _keep_like_the_verify_filter(probs[row], top_k, top_p, min_p)
+ assert torch.equal(torch.isfinite(out[row]), keep)
+ torch.testing.assert_close(out[row][keep], (logits[row] / temperature)[keep])
+
+
+def test_filtered_proposal_keeps_the_rejection_exact():
+ """Zero-q proposals outside the kept support never change the emitted distribution."""
+ from eagle_harness.core.sampled_tree import draw_children, filter_proposal_logits, reject_children
+
+ n = 30000
+ gen = torch.Generator().manual_seed(44)
+ logits = torch.tensor([2.0, 1.5, 0.3, -0.5, -1.0, -3.0]).expand(n, -1)
+ ones = torch.ones(n)
+ filtered = filter_proposal_logits(logits, ones, ones * 2, ones * 0.9, ones * 0)
+ p = torch.tensor([0.05, 0.5, 0.1, 0.0, 0.3, 0.05])
+ draw = draw_children(filtered, torch.arange(6).expand(n, -1), 4, generator=gen)
+ result = reject_children(p.expand(n, -1), draw, torch.rand(n, 4, generator=gen), torch.rand(n, generator=gen))
+ chi_square(result.tokens, p)
diff --git a/tests/test_sampling_check.py b/tests/test_sampling_check.py
index 9d044ae..d100cb7 100644
--- a/tests/test_sampling_check.py
+++ b/tests/test_sampling_check.py
@@ -76,7 +76,7 @@ def test_complete_distribution_evidence_passes(sampling_check, tmp_path):
@pytest.mark.parametrize(
- "fault", ["empty", "missing", "refused", "parameters", "prompts", "samples", "tokens", "unnamed"]
+ "fault", ["empty", "missing", "refused", "parameters", "prompts", "samples", "tokens", "unnamed", "api"]
)
def test_incomplete_distribution_evidence_fails(sampling_check, tmp_path, fault):
ref = artifact()
@@ -90,6 +90,8 @@ def test_incomplete_distribution_evidence_fails(sampling_check, tmp_path, fault)
elif fault == "refused":
setting.clear()
setting["refused"] = "unsupported"
+ elif fault == "api":
+ candidate["api"] = "vllm"
elif fault == "parameters":
setting["params"]["temperature"] = 0.0
elif fault == "prompts":
@@ -288,6 +290,50 @@ def test_score_keeps_as_many_tokens_as_bound_the_cut(sampling_check):
assert len(sampling_check.bounded_top(pairs, 5000, [TOP_K], 2.0)) == 64
[email protected]("api, expected", [("sglang", 0), ("vllm", 1)])
+def test_joint_and_sequential_cuts_use_the_served_engine(sampling_check, tmp_path, api, expected):
+ # Joint top-k=2/top-p=.5 keeps token 1 (.4 mass before it). Top-k-first
+ # excludes it because .4 / (.4 + .3) exceeds .5. No rounding is involved.
+ ref = artifact()
+ ref["api"] = api
+ ref["prompt_ids"] = PROMPTS
+ setting = ref["settings"]["unrestricted"]
+ setting["params"].update(top_k=2, top_p=0.5)
+ setting["tokens"] = [[[1, 1, 1]] * ref["samples"] for _ in PROMPTS]
+ top = [[20.0 + math.log(p), t] for t, p in enumerate([0.4, 0.3, 0.2, 0.1])]
+ scores = {"tolerance_ulps": 0.0, "contexts": {
+ sampling_check.context_key(prompt + [1] * depth): {"vocab": 4, "top": top}
+ for prompt in PROMPTS for depth in range(3)
+ }}
+ assert compare(sampling_check, tmp_path, ref, copy.deepcopy(ref), scores) == expected
+ # Even in joint mode, a token beyond top-k remains an error.
+ bad = copy.deepcopy(ref)
+ bad["settings"]["unrestricted"]["tokens"][0][0] = [3, 1, 1]
+ assert compare(sampling_check, tmp_path, ref, bad, scores) == 1
+
+
[email protected]("joint", [False, True])
+def test_cut_bounds_contain_supported_draws_under_rounding(sampling_check, joint):
+ rng = random.Random(178)
+ for _ in range(100):
+ logits = sorted([rng.uniform(16.0, 24.0) for _ in range(40)], reverse=True)
+ params = dict(TOP_K, top_k=8, top_p=0.7)
+ kept, possible = sampling_check.cut_bounds(
+ [[value, token] for token, value in enumerate(logits)], 40, params, 2.0, joint=joint
+ )
+ moved = [value + rng.uniform(-0.125, 0.125) for value in logits]
+ order = sorted(range(40), key=moved.__getitem__, reverse=True)
+ weights = {token: math.exp(moved[token] - max(moved)) for token in order}
+ total = sum(weights[token] for token in (order if joint else order[:8]))
+ above = 0.0
+ support = set()
+ for token in order[:8]:
+ if above / total < params["top_p"]:
+ support.add(token)
+ above += weights[token]
+ assert kept <= support <= possible
+
+
def test_self_control_passes_through_bf16_cut_flips(sampling_check, tmp_path):
ref, cand = sampled_run(TOP_K, start=1), sampled_run(TOP_K, start=2)
# The flips are real: per draw position, the two starts' supports differ, which failed the old per-token test.
diff --git a/tests/test_sglang_overlap.py b/tests/test_sglang_overlap.py
index 26bed38..6dbdde3 100644
--- a/tests/test_sglang_overlap.py
+++ b/tests/test_sglang_overlap.py
@@ -35,6 +35,7 @@ def test_decode_handoff_uses_the_scheduler_stream_contract(monkeypatch, overlap)
last_width=4,
seeding=False, # the round served the cost model's tree, not a live-cost seed width
timer=None,
+ round_timer=None,
prelaunch=Mock(side_effect=lambda b, **kwargs: (calls.append("prelaunch"), "fence")[1]),
)
worker = SimpleNamespace(
diff --git a/tests/test_sglang_plugin.py b/tests/test_sglang_plugin.py
index dbfbbe9..6942b7b 100644
--- a/tests/test_sglang_plugin.py
+++ b/tests/test_sglang_plugin.py
@@ -609,4 +609,30 @@ def test_draft_attention_splits_keep_the_reference_waves(monkeypatch):
assert [ra.draft_launches(h, cuda)[0].splits for h in (40, 20, 5)] == [16, 32, 128] # TP1, TP2, TP8
assert [ra.draft_launches(h, cuda)[1].splits for h in (40, 20, 5)] == [8, 16, 48]
assert ra.draft_launches(1, cuda)[0].splits == ra.draft_launches(1, cuda)[1].splits == 128 # the cap
+ # A batch multiplies the (request, head) programs: TP1 at batch 4, 8, 32 keeps the waves with fewer splits.
+ assert [ra.draft_launches(bs * 40, cuda)[0].splits for bs in (4, 8, 32)] == [4, 2, 1]
+ assert [ra.draft_launches(bs * 40, cuda)[1].splits for bs in (2, 4, 8, 32)] == [4, 2, 1, 1]
assert ra.draft_launches(10, torch.device("cpu")) == (ra.STEP_LAUNCH, ra.EXTEND_LAUNCH)
+
+
[email protected]("bs,step", [(1, 0), (1, 3), (32, 0), (32, 3)])
+def test_draft_attention_launch_follows_the_batch(monkeypatch, bs, step):
+ """A draft forward takes the launch of its own batch size (captured per batch size), not batch one's."""
+ from eagle_harness.sglang import row_attention as ra
+
+ monkeypatch.setattr(torch.cuda, "get_device_properties", lambda device: SimpleNamespace(multi_processor_count=148))
+ seen = []
+ monkeypatch.setattr(ra, "rows_attention", lambda *args, launch, **kwargs: seen.append(launch))
+ pool = SimpleNamespace(set_kv_buffer=lambda *a: None, get_key_buffer=lambda i: None, get_value_buffer=lambda i: None)
+ backend = ra.DraftRowAttention.__new__(ra.DraftRowAttention)
+ backend.token_to_kv_pool, backend.req_to_token, backend.window = pool, None, 0
+ backend.num_heads, backend.head_dim, backend._device = 40, 8, torch.device("cuda")
+ backend.part_out = backend.part_lse = None
+ rows = 8 if step == 0 else 4
+ backend._group = (rows, step, None, None, None)
+ backend.forward_decode(
+ torch.zeros(bs * rows, 40 * 8), None, None, SimpleNamespace(layer_id=0, scaling=1.0), None, save_kv_cache=False
+ )
+ want = ra.draft_launches(bs * 40, torch.device("cuda"))[0 if step else 1]
+ assert seen == [want]
+ assert want.splits == {(1, 0): 8, (1, 3): 16, (32, 0): 1, (32, 3): 1}[(bs, step)]
diff --git a/tests/test_sglang_sampled_worker.py b/tests/test_sglang_sampled_worker.py
index 31d0abf..a7f0053 100644
--- a/tests/test_sglang_sampled_worker.py
+++ b/tests/test_sglang_sampled_worker.py
@@ -153,3 +153,35 @@ def test_verify_passes_the_tree_sampler_only_for_an_active_sampled_tree(monkeypa
assert step("target", "coins", "final") == ("verify-input", "target", "coins", "final")
else:
assert step is None
+
+
+def _sampled_tree(rows=6):
+ from eagle_harness.sglang.sampled_tree import SampledTree
+
+ shape = SimpleNamespace(max_depth=3, top_k=2, layer_start=lambda depth: 1 + (depth - 1) * 2)
+ tree = SimpleNamespace(shape=shape, tokens=torch.zeros((rows, 9), dtype=torch.int64), max_bs=rows)
+ return SampledTree(tree, 8, 721, rows=rows)
+
+
+def test_prefill_records_each_request_sampling_settings_at_its_slot(monkeypatch):
+ """A prefill stages its requests' sampler settings, so their later proposals follow the target's sampler."""
+ sampled = _sampled_tree()
+ calls = []
+ parent = worker_mod.EagleHarnessWorker.__mro__[1]
+ monkeypatch.setattr(parent, "forward_batch_generation", lambda self, *args, **kwargs: calls.append(args) or "prefilled")
+ worker = worker_mod.EagleHarnessWorker.__new__(worker_mod.EagleHarnessWorker)
+ worker._chain_rounds = SimpleNamespace(interrupt=lambda: None)
+ worker._drafter = SimpleNamespace(cancel_prelaunch=lambda: None)
+ worker._draft_worker = SimpleNamespace(steps=SimpleNamespace(sampled=sampled))
+ sampled.root_valid.fill_(True)
+ info = SimpleNamespace(temperatures=torch.tensor([[0.5], [1.0]]), top_ks=torch.tensor([20, 1 << 30], dtype=torch.int32),
+ top_ps=torch.tensor([0.95, 1.0]), min_ps=torch.tensor([0.0, 0.1]))
+ batch = SimpleNamespace(forward_mode=SimpleNamespace(is_extend=lambda: True), is_extend_in_batch=True,
+ req_pool_indices=torch.tensor([3, 0]), sampling_info=info)
+ assert worker.forward_batch_generation(batch) == "prefilled" and calls
+ identity = torch.tensor([1.0, float(1 << 30), 1.0, 0.0])
+ torch.testing.assert_close(sampled.filters[3], torch.tensor([2.0, 20.0, 0.95, 0.0]))
+ torch.testing.assert_close(sampled.filters[0], torch.tensor([1.0, float(1 << 30), 1.0, 0.1]))
+ for slot in (1, 2, 4, 5):
+ torch.testing.assert_close(sampled.filters[slot], identity)
+ assert sampled.root_valid.tolist() == [False, True, True, False, True, True]
diff --git a/tests/test_verify_tail.py b/tests/test_verify_tail.py
new file mode 100644
index 0000000..e33c96d
--- /dev/null
+++ b/tests/test_verify_tail.py
@@ -0,0 +1,70 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""When :class:`~eagle_harness.sglang.verify_tail.VerifyTail` captures a graph: after a key's eager runs, and only
+over static inputs (the capture itself is faked; ``tests/test_verify_tail_gpu.py`` replays real graphs)."""
+
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+pytest.importorskip("sglang")
+
+from eagle_harness.sglang import verify_tail # noqa: E402
+
+
+class _Graph:
+ def __init__(self):
+ self.replays = 0
+
+ def replay(self):
+ self.replays += 1
+
+
+def captures(monkeypatch):
+ made = []
+
+ def capture(body):
+ made.append(_Graph())
+ return made[-1], body()
+
+ monkeypatch.setattr(verify_tail, "_capture", capture)
+ return made
+
+
+def test_a_key_runs_eagerly_until_its_runs_would_have_paid_for_a_capture(captures):
+ graphs, calls = verify_tail._Graphs(), []
+
+ def body():
+ calls.append(None)
+ return len(calls)
+
+ n = verify_tail.CAPTURE_AFTER
+ outputs = [graphs.run(("bs", 512), body) for _ in range(n + 3)]
+ assert outputs == list(range(1, n + 1)) + [n + 1] * 3 # eager results, then the captured graph's outputs
+ assert len(captures) == 1 and captures[0].replays == 3
+ assert graphs.run(("bs", 511), body) == n + 2 # another batch size starts over, eagerly
+ assert graphs.run(("bs", 512), body, static=False) == n + 3 # inputs a graph would not read: eager
+ assert len(captures) == 1
+
+
+def test_a_selection_is_captured_only_over_the_ranking_graphs_outputs(monkeypatch, captures):
+ monkeypatch.setattr(verify_tail, "CAPTURE_AFTER", 1)
+ tree = SimpleNamespace(
+ rank=lambda bs, depth, count: (torch.arange(count).expand(bs, count), torch.ones(bs, count + 1)),
+ select=lambda bs, steps, ranked, width: ranked[:, : width - 1].clone(),
+ )
+ tail = verify_tail.VerifyTail(tree, lambda bs, selection, steps, width: selection)
+ eager = tail.rank(2, 3, 5)
+ for _ in range(3): # an eager ranking's tensors are not the ones a later round refills
+ tail.verify_input(2, 3, 4, eager)
+ assert not captures
+ ranking = tail.rank(2, 3, 5) # second run: captured
+ assert len(captures) == 1 and ranking is tail.rank(2, 3, 5)
+ tail.verify_input(2, 3, 4, ranking)
+ tail.verify_input(2, 3, 4, ranking)
+ assert len(captures) == 2
+ tail.verify_input(2, 3, 4, eager) # the selection graph reads the ranking graph's buffers: not these
+ assert captures[1].replays == 1
diff --git a/tests/test_verify_tail_gpu.py b/tests/test_verify_tail_gpu.py
index 214ed0b..bc2e202 100644
--- a/tests/test_verify_tail_gpu.py
+++ b/tests/test_verify_tail_gpu.py
@@ -12,6 +12,7 @@ import torch
pytest.importorskip("sglang")
from eagle_harness.core.draft_tree import DraftTree, TreeShape # noqa: E402
+from eagle_harness.sglang import verify_tail # noqa: E402
from eagle_harness.sglang.verify_tail import VerifyTail # noqa: E402
pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device")
@@ -45,13 +46,14 @@ def _build(bs, selection, steps, width):
@pytest.mark.parametrize("bs,depth,width", [(1, 6, 16), (1, 4, 8), (3, 7, 16)])
-def test_replayed_ranking_and_selection_follow_the_trees_buffers(bs, depth, width):
+def test_replayed_ranking_and_selection_follow_the_trees_buffers(monkeypatch, bs, depth, width):
+ monkeypatch.setattr(verify_tail, "CAPTURE_AFTER", 1) # each graph: an eager round, a capture, then replays
tree = _drafted_tree(bs, depth, seed=1)
tail = VerifyTail(tree, _build)
count = min(tree.shape.num_nodes(depth), 15)
- for seed in (1, 2): # the second round refills the same static buffers with another tree
- if seed == 2:
- other = _drafted_tree(bs, depth, seed=2)
+ for seed in (1, 2, 3, 4): # later rounds refill the same static buffers with another tree
+ if seed > 1:
+ other = _drafted_tree(bs, depth, seed=seed)
for name in ("scores", "tokens", "parents"):
getattr(tree, name).copy_(getattr(other, name))
ranking = tail.rank(bs, depth, count)
diff --git a/tests/test_worker_rounds.py b/tests/test_worker_rounds.py
index 1cfc457..ac5868e 100644
--- a/tests/test_worker_rounds.py
+++ b/tests/test_worker_rounds.py
@@ -166,6 +166,7 @@ def make_worker(modules, monkeypatch, *, calibration=None, schedule=None, native
draft=draft,
last_width=4,
timer=None,
+ round_timer=None,
seeding=False,
prelaunch=prelaunch,
)
@@ -215,8 +216,9 @@ def make_worker(modules, monkeypatch, *, calibration=None, schedule=None, native
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)
+ invalidated, settings = [], []
+ sampled = SimpleNamespace(active=False, root_valid=torch.ones(8, dtype=torch.bool), invalidate=invalidated.append,
+ set_sampling=lambda slots, info: settings.append((slots, info)))
worker._draft_worker.steps = SimpleNamespace(sampled=sampled)
monkeypatch.setattr(modules.base, "forward_batch_generation", lambda self, *args: "prefill", raising=False)
@@ -240,6 +242,7 @@ def test_sampled_tree_follows_the_batch_and_never_verifies_roots_drafted_without
prefill = batch(1.0, mode=Mode.EXTEND)
assert worker.forward_batch_generation(prefill) == "prefill"
assert invalidated == [prefill.req_pool_indices]
+ assert settings == [(prefill.req_pool_indices, prefill.sampling_info)] # its requests' proposals follow their sampler
@pytest.mark.parametrize("overlap", [False, True])
@@ -394,6 +397,9 @@ def test_attention_initialization_wires_the_same_width_plan_into_both_routes(mod
def __init__(self, *args, chain_width, **kwargs):
self.chain_width = chain_width
+ def warm_up(self, batch_sizes):
+ self.warmed = list(batch_sizes)
+
module = modules.worker
monkeypatch.setattr(modules.base, "init_attention_backends", lambda self: None, raising=False)
monkeypatch.setattr(module, "DynamicDrafter", Draft)
diff --git a/tools/sampling_check.py b/tools/sampling_check.py
index 18f53b9..0e699d7 100644
--- a/tools/sampling_check.py
+++ b/tools/sampling_check.py
@@ -293,13 +293,15 @@ def _sibling(name: str):
return sys.modules[name]
-def cut_bounds(top: Sequence[Sequence[float]], vocab: int, params: dict, tolerance_ulps: float) -> Tuple[Set, Set]:
+def cut_bounds(
+ top: Sequence[Sequence[float]], vocab: int, params: dict, tolerance_ulps: float, *, joint: bool = False
+) -> Tuple[Set, Set]:
"""(tokens every tolerated logit keeps, tokens some tolerated logit keeps) under the setting's cut.
``top``: fp32 ``[logit, token]`` pairs, best first; the ``vocab - len(top)`` other tokens are at most the last
logit. Each logit may move by ``tolerance_ulps / 2`` bf16 ulps at its magnitude, so the gap of a pair moves by up
- to ``tolerance_ulps`` (the fp32 arbiter's rule). The cut is top-k, then top-p on the renormalized top-k
- distribution at the setting's temperature, or min-p alone (vLLM's and sglang's order)."""
+ to ``tolerance_ulps`` (the fp32 arbiter's rule). SGLang applies top-k and top-p jointly to the full
+ distribution. Otherwise top-p uses the renormalized top-k distribution. Min-p alone is also supported."""
ulp = _sibling("fp32_arbiter").bf16_ulp
temperature, k, top_p, min_p = params["temperature"], params["top_k"], params["top_p"], params["min_p"]
k = None if k in (-1, 0) else k
@@ -331,10 +333,11 @@ def cut_bounds(top: Sequence[Sequence[float]], vocab: int, params: dict, toleran
above_hi, above_lo = counter(hi), counter(lo)
# In the top k for every tolerated logit (fewer than k others can reach it) / for some (fewer than k others are
- # surely above it). Only these tokens enter the top-p sums.
+ # surely above it). Joint top-p uses all tokens, independently of the top-k cut.
in_k = [k is None or above_hi(lo[i]) - count[i] < k for i in range(n)]
maybe_k = [count[i] > 0 and (k is None or above_lo(hi[i]) < k) for i in range(n)]
- pool = [j for j in range(n) if maybe_k[j]]
+ in_p = [joint or keep for keep in in_k]
+ pool = [j for j in range(n) if joint or maybe_k[j]]
by_hi = sorted(range(n), key=lambda j: hi[j], reverse=True)[:2] # the two largest bounds of each side, for min-p
by_lo = sorted(range(n), key=lambda j: lo[j], reverse=True)[:2]
kept, possible = [], []
@@ -344,9 +347,9 @@ def cut_bounds(top: Sequence[Sequence[float]], vocab: int, params: dict, toleran
# Kept when the renormalized mass of the tokens above it is below top_p: bound that share both ways.
others = [j for j in pool if j != i]
above_max = sum(count[j] * mass(hi[j]) for j in others if hi[j] > lo[i])
- below_min = mass(lo[i]) + sum(count[j] * mass(lo[j]) for j in others if hi[j] < lo[i] and in_k[j])
+ below_min = mass(lo[i]) + sum(count[j] * mass(lo[j]) for j in others if hi[j] < lo[i] and in_p[j])
sure = sure and above_max / (above_max + below_min) < top_p
- above_min = sum(count[j] * mass(lo[j]) for j in others if lo[j] > hi[i] and in_k[j])
+ above_min = sum(count[j] * mass(lo[j]) for j in others if lo[j] > hi[i] and in_p[j])
rest_max = count[i] * mass(hi[i]) + sum(count[j] * mass(hi[j]) for j in others if lo[j] <= hi[i])
maybe = above_min / (above_min + rest_max) < top_p
if min_p > 0.0:
@@ -384,12 +387,13 @@ def context_key(ids: Sequence[int]) -> str:
def bounded_top(pairs: Sequence[Sequence[float]], vocab: int, settings: Sequence[dict], tolerance_ulps: float) -> list:
- """The shortest head of ``pairs`` (fp32 ``[logit, token]``, best first) that bounds every setting's cut."""
+ """The shortest head of ``pairs`` that bounds every setting for both joint and sequential filtering."""
size = min(64, len(pairs))
while True:
try:
for params in settings:
- cut_bounds(pairs[:size], vocab, params, tolerance_ulps)
+ for joint in (False, True):
+ cut_bounds(pairs[:size], vocab, params, tolerance_ulps, joint=joint)
return list(pairs[:size])
except ValueError:
if size == len(pairs):
@@ -428,6 +432,8 @@ def score(args) -> int:
def validate_pair(ref: dict, cand: dict) -> None:
"""Reject partial evidence before a statistical test can silently omit it."""
+ if ref.get("api") != cand.get("api"):
+ raise ValueError("reference and candidate must use the same engine API")
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"]
@@ -485,6 +491,8 @@ def cut_tests(
scores: dict,
tally: List[int],
outside: list,
+ *,
+ joint: bool = False,
) -> list:
"""A truncated setting's tests at its judged contexts, on the draws among the tokens every tolerated logit keeps.
Counts near-tie and outside draws into ``tally`` and lists the outside tokens in ``outside``."""
@@ -494,7 +502,9 @@ def cut_tests(
context = scores["contexts"].get(context_key(list(prompt_ids) + list(prefix)))
if context is None:
raise ValueError(f"{name}: prompt {prompt} prefix {list(prefix)} was not scored")
- kept, possible = cut_bounds(context["top"], context["vocab"], params, scores["tolerance_ulps"])
+ kept, possible = cut_bounds(
+ context["top"], context["vocab"], params, scores["tolerance_ulps"], joint=joint
+ )
draws = [[t[depth] for t in tokens if tuple(t[:depth]) == prefix] for tokens in (r_tokens, c_tokens)]
what = "token 1" if depth == 0 else f"token {depth + 1} | modal prefix"
tests.append((name, prompt, what, *homogeneity(*[[t for t in d if t in kept] for d in draws])))
@@ -531,9 +541,13 @@ def compare(args) -> int:
raise ValueError(f"{name} truncates: judge it with --scores (see score)")
for i, (r_tokens, c_tokens) in enumerate(zip(ref["settings"][name]["tokens"], entry["tokens"])):
if truncates(params):
+ assert scores is not None
tally = cuts.setdefault(name, [0, 0, 0, 0])
prompt_ids = ref["prompt_ids"][i]
- tests += cut_tests(name, params, i, prompt_ids, r_tokens, c_tokens, scores, tally, outside)
+ tests += cut_tests(
+ name, params, i, prompt_ids, r_tokens, c_tokens, scores, tally, outside,
+ joint=ref.get("api") == "sglang",
+ )
else:
tests += mixed_tests(name, i, r_tokens, c_tokens)
except (KeyError, ValueError) as error: # unscored contexts, or a cut the scores cannot bound