Skip to content

Official Inference Code of EAGLE-4

fix(vllm): measure served tree acceptance and select the batch-size switch from weighted gains

Seyfal Sultanov576d5ef6d5b9
diff --git a/docs/configuration.md b/docs/configuration.md
index 634c23b..3721946 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -82,11 +82,13 @@ vLLM takes these extra keys in `method_config`:
| `node_top_k` | integer | `8` (trees), `1` (chains) | Frontier nodes expanded per draft step. `1` uses vLLM's own EAGLE chain loop. |
| `tree_depth` | integer | `12` (trees), `15` (chains) | Maximum draft depth. It sizes the draft's KV lookahead. |
| `depth_stop_gain` | `"derived"`, number or `null` | `"derived"` | What one more draft step must add to the expected accepted length. `"derived"`: the step's measured cost from the cost tables under `data_path`, or a startup error in automatic serving when a scheduled shape is unpriced. Static mode retains a lossless stop. A number sets a fixed gain. `0` stops only when no deeper node can enter the verify set. `null` always drafts `tree_depth` steps. |
+| `record_rounds` | boolean | `false` | Trees: time the served decode rounds and merge them into `<data_path>/rounds/tree.json`, per batch size and verify width: the median round period and the mean tokens committed per request-round, as vLLM's spec-decode counters report it (rounds that also prefill included). Needs `data_path`. Serve the workload once per candidate `max_verify_width`; each server keeps the other widths' rows. |
In `serve` mode vLLM fixes the verify width per batch size (`num_speculative_tokens_per_batch_size`).
Automatic trees require cost tables for every scheduled shape; set `depth_stop_gain` explicitly to opt out.
Automatic chains require timings and an acceptance profile; an explicit `max_verify_width` or batch schedule opts into unpriced operation.
-Trees get the widest graph width of their cost buckets. A chain (`node_top_k` 1) verifies exactly its width, so the
+Trees get the widest graph width of their cost buckets, capped from the first batch size where
+`<data_path>/rounds/tree.json` measured a narrower verify faster (as in static mode). A chain (`node_top_k` 1) verifies exactly its width, so the
width of each batch size is derived from the cost tables and the chain acceptance profile under `data_path`
(`<data_path>/accept/chain.json`): the width with the most expected tokens per unit of time, `1` (no speculation) when
no chain pays. Without a profile startup fails, unless `max_verify_width` or a batch schedule is explicitly supplied. See
diff --git a/eagle_harness/core/chain_width.py b/eagle_harness/core/chain_width.py
index 4199de4..be00518 100644
--- a/eagle_harness/core/chain_width.py
+++ b/eagle_harness/core/chain_width.py
@@ -39,6 +39,7 @@ starting a separate engine. The width of batch size ``B`` is then
from __future__ import annotations
import json
+import math
import os
import statistics
from dataclasses import dataclass
@@ -271,7 +272,8 @@ def _ranges(widths: Mapping[int, int], max_batch_size: int) -> List[Tuple[int, i
# {"rounds": [{"batch_size": 64, "width": 16, "round_us": 47900.0, "accept": 3.96, "count": 200}, ...]}
#
# per batch size and verify width: the median period between consecutive decode rounds and the mean tokens a request
-# committed per round (``accept``: 1 + accepted drafts). Width 1 verifies only the root (no drafts). Unlike the chain's
+# committed per round it verified drafts in, rounds that also prefill included (``accept``: 1 + accepted drafts, as
+# vLLM's spec-decode counters report it). Width 1 verifies only the root (no drafts). Unlike the chain's
# acceptance profile, the tree's acceptance is measured per width, since the best ``width`` nodes of a tree are not a
# prefix of a chain.
@@ -286,8 +288,8 @@ def _check_tree_row(row: Mapping[str, float]) -> None:
def load_tree_rounds(
data_path: str, key: Optional[CostKey] = None
-) -> Optional[Dict[int, Dict[int, Tuple[float, float]]]]:
- """``{batch size: {width: (round us, accept)}}`` from ``<data_path>/rounds/tree.json``, None if not measured.
+) -> Optional[Dict[int, Dict[int, Tuple[float, float, int]]]]:
+ """``{batch size: {width: (round us, accept, rounds)}}`` from ``<data_path>/rounds/tree.json``, None if not measured.
With the server's ``key``, rounds measured on another setup are refused (as by :func:`chain_widths`)."""
try:
with open(os.path.join(data_path, TREE_ROUNDS_FILE), encoding="utf-8") as f:
@@ -296,10 +298,10 @@ def load_tree_rounds(
return None
if key is not None:
check_key(data_path, key)
- rounds: Dict[int, Dict[int, Tuple[float, float]]] = {}
+ rounds: Dict[int, Dict[int, Tuple[float, float, int]]] = {}
for row in rows:
_check_tree_row(row)
- cell = (float(row["round_us"]), float(row["accept"]))
+ cell = (float(row["round_us"]), float(row["accept"]), int(row["count"]))
rounds.setdefault(int(row["batch_size"]), {})[int(row["width"])] = cell
return rounds
@@ -328,30 +330,39 @@ def merge_tree_rounds(data_path: str, rows: Sequence[Mapping[str, float]]) -> st
def served_tree_schedule(
- rounds: Mapping[int, Mapping[int, Tuple[float, float]]], width: int, max_batch_size: int
+ rounds: Mapping[int, Mapping[int, Tuple[float, float, int]]], width: int, max_batch_size: int
) -> Optional[List[Tuple[int, int, int]]]:
"""``(first, last, verify width)`` ranges over ``1..max_batch_size`` for a tree configured ``width`` wide.
- At each measured batch size that timed ``width``, the measured width up to ``width`` with the most tokens per unit
- of time (``accept / round_us``; ties keep the wider). Every batch size below the first measured one where another
- width wins keeps ``width``, so the low-batch behavior never changes; from there each batch size takes the choice of
- the nearest measured one (ties go to the larger). None when no measured batch size beats ``width``: the tree then
- keeps one width, as without measurements.
+ A measured batch size that timed ``width`` and a narrower width compares them by tokens per unit of time
+ (``accept / round_us``): its choice is the narrower width with the highest rate (ties keep the wider), and its gain
+ is the log of that rate over ``width``'s, weighted by the fewer rounds of the two cells. A wider verify only gets
+ dearer relative to a narrower one as the batch grows, so the schedule keeps ``width`` below one switch batch size
+ and narrows from there: the switch is the compared batch size whose gain summed with every larger one's is the
+ largest (ties go to the larger switch). A few rounds of a nearly drained batch, whose remaining requests differ
+ between the calibration servers, then cannot move the low-batch width. From the switch each batch size takes the
+ choice of the nearest compared one (ties go to the larger), never wider than a smaller batch size's. None when no
+ switch gains: the tree then keeps one width, as without measurements.
"""
- choices: Dict[int, int] = {}
+ compared: Dict[int, Tuple[int, float]] = {} # batch size -> (narrower choice, weighted log gain)
for bs, cells in rounds.items():
- if width not in cells:
+ narrower = [(accept / us, w, count) for w, (us, accept, count) in cells.items() if w < width]
+ if width not in cells or not narrower:
continue
- best, best_rate = width, cells[width][1] / cells[width][0]
- for w, (us, accept) in sorted(cells.items(), reverse=True):
- if w <= width and accept / us > best_rate:
- best, best_rate = w, accept / us
- choices[bs] = best
- losing = [bs for bs, best in choices.items() if best != width]
- if not losing:
+ us, accept, count = cells[width]
+ rate, best, best_count = max(narrower)
+ compared[bs] = (best, min(count, best_count) * math.log(rate * us / accept))
+ switch, total, best_total = None, 0.0, 0.0
+ for bs in sorted(compared, reverse=True):
+ total += compared[bs][1]
+ if total > best_total:
+ switch, best_total = bs, total
+ if switch is None:
return None
- switch = min(losing)
- ranges = _ranges({bs: w for bs, w in choices.items() if bs >= switch}, max_batch_size)
+ ranges = _ranges({bs: best for bs, (best, _) in compared.items() if bs >= switch}, max_batch_size)
kept = [(1, switch - 1, width)] if switch > 1 else []
- clipped = [(max(first, switch), last, w) for first, last, w in ranges if last >= switch]
- return merge_ranges(kept + clipped)
+ narrowed: List[Tuple[int, int, int]] = []
+ for first, last, w in ranges:
+ if last >= switch:
+ narrowed.append((max(first, switch), last, min(w, narrowed[-1][2]) if narrowed else w))
+ return merge_ranges(kept + narrowed)
diff --git a/eagle_harness/vllm/config.py b/eagle_harness/vllm/config.py
index adb4eed..cc550c8 100644
--- a/eagle_harness/vllm/config.py
+++ b/eagle_harness/vllm/config.py
@@ -25,7 +25,8 @@ sglang takes from its own server arguments, and one of the vLLM tree drafter:
``<data_path>/rounds/tree.json`` (:mod:`eagle_harness.vllm.round_recorder`). A tree whose
``data_path`` holds those rounds verifies fewer rows from the first batch size where that
measured faster (:func:`~eagle_harness.core.chain_width.served_tree_schedule`); smaller batches
- keep ``max_verify_width``.
+ keep ``max_verify_width``. In the cost-model modes the measured width also caps each batch
+ size's verify bucket.
Example::
@@ -51,6 +52,7 @@ from eagle_harness.core.chain_width import (
load_tree_rounds,
merge_ranges,
served_tree_schedule,
+ width_at,
)
from eagle_harness.core.config import HarnessConfig, harness_config_from_dict
from eagle_harness.core.limits import (
@@ -175,9 +177,24 @@ def _verify_widths(
)
if widths is None:
widths = [(bs, bs, min(max(verify_buckets(bs, intensity)), max_verify_width)) for bs in cost_batch_sizes(limit)]
+ measured = None if chain else measured_tree_widths(data_path, max_verify_width, limit, key)
+ if measured is not None:
+ widths = _narrowest(widths, measured)
return widths
+def _narrowest(widths: List[Tuple[int, int, int]], measured: List[Tuple[int, int, int]]) -> List[Tuple[int, int, int]]:
+ """Per batch size, the narrower of two schedules: ``widths`` per calibrated batch size (each covers the batch sizes
+ after the previous one) and ``measured`` ranges."""
+ firsts = [1] + [last + 1 for _, last, _ in widths[:-1]]
+ buckets = [(first, last, width) for first, (_, last, width) in zip(firsts, widths)]
+ cuts = sorted({first for first, _, _ in buckets} | {first for first, _, _ in measured if first <= widths[-1][1]})
+ ends = [cut - 1 for cut in cuts[1:]] + [widths[-1][1]]
+ return merge_ranges(
+ (first, last, min(width_at(buckets, first), width_at(measured, first))) for first, last in zip(cuts, ends)
+ )
+
+
def _draft_token_schedule(widths: List[Tuple[int, int, int]], limit: int) -> List[Tuple[int, int, int]]:
# each range starts after the previous one: tree widths come per calibrated batch size, with gaps between them
firsts = [1] + [last + 1 for _, last, _ in widths[:-1]]
@@ -292,19 +309,26 @@ def native_decode_ranges(spec_config: Any) -> List[Tuple[int, int]]:
def measured_tree_schedule(parsed: VllmMethodConfig, key: CostKey | None = None) -> List[Tuple[int, int, int]] | None:
"""The static tree's draft-count schedule from served rounds under ``data_path`` (None: one width throughout)."""
- data_path = parsed.harness.data_path
+ limit = max_batch_size(parsed.harness.intensity)
+ widths = measured_tree_widths(parsed.harness.data_path, parsed.max_verify_width, limit, key)
+ return None if widths is None else _draft_token_schedule(widths, limit)
+
+
+def measured_tree_widths(
+ data_path: str | None, max_verify_width: int, limit: int, key: CostKey | None = None
+) -> List[Tuple[int, int, int]] | None:
+ """The tree's verify width ranges from served rounds under ``data_path`` (None: one width throughout)."""
rounds = load_tree_rounds(data_path, key) if data_path else None
if not rounds:
return None
- limit = max_batch_size(parsed.harness.intensity)
- widths = served_tree_schedule(rounds, parsed.max_verify_width, limit)
+ widths = served_tree_schedule(rounds, max_verify_width, limit)
if widths is None:
return None
path = os.path.join(data_path, TREE_ROUNDS_FILE)
with open(path, "rb") as f:
digest = hashlib.sha256(f.read()).hexdigest()
logger.info("eagle_harness: tree verify width per batch size from %s (sha256 %s): %s", path, digest, widths)
- return _draft_token_schedule(widths, limit)
+ return widths
def check_data_key(spec_config: Any, key: CostKey) -> None:
diff --git a/eagle_harness/vllm/round_recorder.py b/eagle_harness/vllm/round_recorder.py
index b349f7c..0526630 100644
--- a/eagle_harness/vllm/round_recorder.py
+++ b/eagle_harness/vllm/round_recorder.py
@@ -7,11 +7,18 @@ vLLM fixes a round's verify width from its batch size, so a server times only th
a width by serving the workload once with ``max_verify_width`` set to it and ``record_rounds`` on, then the next
width; every server merges its cells into ``<data_path>/rounds/tree.json`` and keeps the others.
-The speculator calls :meth:`ServedRoundRecorder.round` once per ``propose``. The period from one call to the next
-holds the draft growth of ``count`` rows and the verify of ``count + 1`` rows that follows it, plus the scheduler and
-the launches between them, so it is recorded as one round of width ``count + 1`` when both calls saw the same batch
-size, the previous call's ``count`` and no prefill. ``num_sampled`` (tokens each request committed in the verify just
-finished) is summed on the device; only :meth:`rows` reads it back, once per flush.
+The speculator calls :meth:`ServedRoundRecorder.round` once per ``propose``. A cell is a call's batch size and the
+``count + 1`` rows it drafts, which the next forward verifies. Its two values cover different rounds:
+
+- ``round_us``: the median period from one call to the next when both calls saw the same batch size and no prefill.
+ The period holds the draft growth of ``count`` rows and the verify of ``count + 1`` rows that follows it, plus the
+ scheduler and the launches between them; a prefill's own work would inflate it.
+- ``accept``: the mean tokens committed per request that verified drafts, over every verify of the cell's drafts,
+ prefills included. A batch that also prefills verifies its drafts as chains, which commits fewer tokens than a tree
+ of the same rows, and vLLM's spec-decode counters include those rounds: this is the acceptance served at that width.
+
+``num_sampled`` (tokens each request committed in the verify just finished) is summed on the device; only :meth:`rows`
+reads it back, once per flush.
"""
from __future__ import annotations
@@ -21,7 +28,7 @@ import statistics
import time
from collections import defaultdict
from collections.abc import Callable
-from typing import ContextManager
+from typing import ContextManager, NamedTuple
import torch
@@ -31,6 +38,13 @@ FLUSH_ROUNDS = 256
MIN_ROUNDS = 8
+class _Call(NamedTuple):
+ num_reqs: int
+ count: int
+ has_prefill: bool
+ time: float
+
+
class ServedRoundRecorder:
def __init__(
self,
@@ -50,29 +64,35 @@ class ServedRoundRecorder:
self.min_rounds = min_rounds
self.clock = clock
self.sync_allowed = sync_allowed
- self._last: tuple[int, int] | None = None # (batch size, count) of the previous decode call
- self._last_t = 0.0
+ self._last: _Call | None = None
self._periods: dict[tuple[int, int], list[float]] = defaultdict(list)
- self._tokens: dict[tuple[int, int], torch.Tensor] = {} # committed tokens, on the device
+ # per cell, on the device: (tokens committed, requests that verified drafts)
+ self._tokens: dict[tuple[int, int], torch.Tensor] = {}
self._recorded = 0
- def round(self, num_reqs: int, count: int, has_prefill: bool, num_sampled: torch.Tensor) -> None:
- """One ``propose`` call: ``count`` rows to draft now, ``num_sampled[:num_reqs]`` from the verify just done."""
+ def round(
+ self, num_reqs: int, count: int, has_prefill: bool, num_sampled: torch.Tensor, cu_num_logits: torch.Tensor
+ ) -> None:
+ """One ``propose`` call: ``count`` rows to draft now; ``num_sampled[:num_reqs]`` and the logits rows per request
+ (``cu_num_logits``: one more than its drafts) of the verify just done."""
now = self.clock()
last = self._last
- if not has_prefill and last is not None and last[0] == num_reqs:
- key = (num_reqs, last[1] + 1)
- self._periods[key].append(now - self._last_t)
- committed = num_sampled[:num_reqs].sum(dtype=torch.int64)
+ if last is not None:
+ key = (last.num_reqs, last.count + 1)
+ verified = (cu_num_logits[1 : num_reqs + 1] - cu_num_logits[:num_reqs]) > 1
+ sums = torch.stack(
+ (torch.where(verified, num_sampled[:num_reqs], 0).sum(dtype=torch.int64), verified.sum(dtype=torch.int64))
+ )
if key in self._tokens:
- self._tokens[key] += committed
+ self._tokens[key] += sums
else:
- self._tokens[key] = committed.clone()
- self._recorded += 1
- if self.writer and self._recorded % self.flush_rounds == 0:
- self.flush()
- self._last = None if has_prefill else (num_reqs, count)
- self._last_t = now
+ self._tokens[key] = sums
+ if not has_prefill and not last.has_prefill and last.num_reqs == num_reqs:
+ self._periods[key].append(now - last.time)
+ self._recorded += 1
+ if self.writer and self._recorded % self.flush_rounds == 0:
+ self.flush()
+ self._last = _Call(num_reqs, count, has_prefill, now)
def rows(self) -> list[dict]:
"""The cells timed at least ``min_rounds`` times (reads the device sums back)."""
@@ -80,7 +100,10 @@ class ServedRoundRecorder:
for (bs, width), periods in sorted(self._periods.items()):
if len(periods) < self.min_rounds:
continue
- accept = int(self._tokens[(bs, width)].item()) / (bs * len(periods))
+ tokens, requests = self._tokens[(bs, width)].tolist()
+ if not requests:
+ continue
+ accept = tokens / requests
out.append(
{
"batch_size": bs,
diff --git a/eagle_harness/vllm/speculator.py b/eagle_harness/vllm/speculator.py
index c7ad693..91c82c2 100644
--- a/eagle_harness/vllm/speculator.py
+++ b/eagle_harness/vllm/speculator.py
@@ -290,7 +290,7 @@ class HarnessSpeculator(EagleSpeculator):
count = self.num_speculative_steps if num_speculative_tokens is None else num_speculative_tokens
num_reqs = input_batch.num_reqs
if self.recorder is not None and not dummy_run:
- self.recorder.round(num_reqs, count, bool(input_batch.has_prefill), num_sampled)
+ self.recorder.round(num_reqs, count, bool(input_batch.has_prefill), num_sampled, input_batch.cu_num_logits)
if not dummy_run and self.sampled_tokens is not None:
# Rows in path order: the draft prefill then sees the accepted chain, a prefix of the rows.
self.src_rows.copy_(self.rows) # rows that are not a verified tree keep their place
diff --git a/tests/test_live_costs.py b/tests/test_live_costs.py
index 00b4e12..f0650fd 100644
--- a/tests/test_live_costs.py
+++ b/tests/test_live_costs.py
@@ -161,7 +161,7 @@ def test_every_calibration_reader_refuses_another_setup(tmp_path):
chain = SimpleNamespace(method_config={"intensity": "chain_intensity", "data_path": data_path})
tree = SimpleNamespace(method_config={"mode": "static", "max_verify_width": 16, "data_path": data_path})
assert chain_widths(data_path, 4, 8, key=b300) == [(1, 8, 4)]
- assert load_tree_rounds(data_path, b300) == {64: {16: (48000.0, 4.0)}}
+ assert load_tree_rounds(data_path, b300) == {64: {16: (48000.0, 4.0, 10)}}
check_data_key(chain, b300)
check_data_key(tree, b300)
for read in (
diff --git a/tests/test_tree_load_policy.py b/tests/test_tree_load_policy.py
index 9fd16c1..aed809e 100644
--- a/tests/test_tree_load_policy.py
+++ b/tests/test_tree_load_policy.py
@@ -38,7 +38,7 @@ RELEASE = [
def _rounds(rows):
out = {}
for r in rows:
- out.setdefault(r["batch_size"], {})[r["width"]] = (r["round_us"], r["accept"])
+ out.setdefault(r["batch_size"], {})[r["width"]] = (r["round_us"], r["accept"], r["count"])
return out
@@ -67,6 +67,29 @@ def test_low_batch_keeps_the_configured_width_and_high_batch_narrows():
assert schedule[0][0] == 1 and schedule[-1][1] == 512
+def test_a_few_rounds_of_a_drained_batch_do_not_move_the_low_batch_width():
+ """TP1 calibration shape: the tails of two passes leave a few rounds at batch sizes 2-7 where the remaining requests
+ differ between the servers. Thousands of rounds at batch 8 say 16 wins there; the switch stays above it."""
+ rows = [
+ _row(1, 16, 14_218, 9.91, 63), _row(1, 4, 11_611, 3.35, 163),
+ _row(2, 16, 12_000, 2.11, 21), _row(2, 4, 12_125, 2.30, 21),
+ _row(6, 16, 19_888, 2.96, 99), _row(6, 4, 15_727, 2.52, 77),
+ _row(7, 16, 22_581, 3.17, 31), _row(7, 4, 17_605, 2.73, 70),
+ _row(8, 16, 23_073, 4.51, 1654), _row(8, 4, 16_550, 2.81, 2834),
+ _row(20, 16, 39_769, 3.75, 53), _row(20, 4, 19_500, 2.50, 40),
+ _row(42, 16, 70_849, 4.12, 212),
+ _row(43, 16, 72_997, 4.34, 247), _row(43, 4, 27_000, 2.70, 30),
+ ]
+ assert served_tree_schedule(_rounds(rows), 16, 512) == [(1, 19, 16), (20, 512, 4)]
+
+
+def test_narrowing_never_widens_at_a_larger_batch():
+ rows = RELEASE + [_row(256, 16, 150_000, 3.9), _row(256, 4, 40_000, 2.8), _row(256, 2, 25_000, 1.9)]
+ rows += [_row(512, 16, 300_000, 3.9), _row(512, 4, 70_000, 2.8), _row(512, 2, 60_000, 1.9)]
+ schedule = served_tree_schedule(_rounds(rows), 16, 512)
+ assert (width_at(schedule, 64), width_at(schedule, 256), width_at(schedule, 512)) == (4, 2, 2)
+
+
def test_batch_sizes_below_the_first_loss_keep_the_configured_width():
# Only batch 64 was measured: everything below it keeps 16, even batch sizes nearer to nothing else.
rows = [r for r in RELEASE if r["batch_size"] == 64]
@@ -96,7 +119,7 @@ def test_merge_keeps_other_widths_and_replaces_measured_cells(tmp_path):
merge_tree_rounds(str(tmp_path), [_row(8, 16, 12_000, 4.4), _row(64, 16, 48_000, 3.9)])
merge_tree_rounds(str(tmp_path), [_row(64, 16, 47_900, 3.96), _row(64, 4, 20_000, 2.9)])
rounds = load_tree_rounds(str(tmp_path))
- assert rounds == {8: {16: (12_000.0, 4.4)}, 64: {16: (47_900.0, 3.96), 4: (20_000.0, 2.9)}}
+ assert rounds == {8: {16: (12_000.0, 4.4, 50)}, 64: {16: (47_900.0, 3.96, 50), 4: (20_000.0, 2.9, 50)}}
data = json.loads((tmp_path / TREE_ROUNDS_FILE).read_text())
assert sorted((r["batch_size"], r["width"]) for r in data["rounds"]) == [(8, 16), (64, 4), (64, 16)]
diff --git a/tests/test_vllm_plugin.py b/tests/test_vllm_plugin.py
index f6000ab..64e93d2 100644
--- a/tests/test_vllm_plugin.py
+++ b/tests/test_vllm_plugin.py
@@ -312,6 +312,33 @@ def test_measured_tree_rounds_narrow_only_the_losing_batch_sizes(registered, tmp
assert plain.num_speculative_tokens_per_batch_size is None
+def test_measured_tree_rounds_cap_the_serve_mode_buckets(registered, tmp_path):
+ from eagle_harness.core.chain_width import merge_tree_rounds
+
+ def row(bs, width, round_us, accept):
+ return {"batch_size": bs, "width": width, "round_us": round_us, "accept": accept, "count": 50}
+
+ tree = {"mode": "serve", "node_top_k": 4, "tree_depth": 14, "max_verify_width": 16, "data_path": str(tmp_path)}
+ unmeasured = SpeculativeConfig(method=METHOD_NAME, method_config=tree).num_speculative_tokens_per_batch_size
+ merge_tree_rounds(
+ str(tmp_path),
+ [row(8, 16, 12_500, 4.43), row(8, 4, 9_000, 2.9), row(64, 16, 47_900, 3.96), row(64, 4, 20_000, 2.9)],
+ )
+ config = SpeculativeConfig(method=METHOD_NAME, method_config=tree)
+ schedule = config.num_speculative_tokens_per_batch_size
+ assert validate_and_normalize_dynamic_sd_schedule(schedule) == schedule
+
+ def k_at(entries, bs):
+ return next(k for first, last, k in entries if first <= bs <= last)
+
+ # Below the first measured loss (batch 64) the buckets stand; from there width 4 caps them.
+ for bs in (1, 2, 8, 16, 63):
+ assert k_at(schedule, bs) == k_at(unmeasured, bs)
+ assert {k_at(schedule, bs) for bs in (64, 128, 512)} == {3}
+ assert {k_at(unmeasured, bs) for bs in (64, 128, 512)} != {3}
+ assert config.num_speculative_tokens == max(k for _, _, k in schedule)
+
+
def test_record_rounds_needs_a_data_path():
assert parse_method_config({"mode": "static", "record_rounds": True, "data_path": "/x"}).record_rounds is True
assert parse_method_config({"mode": "static"}).record_rounds is False
diff --git a/tests/test_vllm_round_recorder.py b/tests/test_vllm_round_recorder.py
index a9d9b8d..5a4d4c0 100644
--- a/tests/test_vllm_round_recorder.py
+++ b/tests/test_vllm_round_recorder.py
@@ -19,10 +19,15 @@ class Clock:
return self.now
+def _logits(rows_per_req):
+ """``cu_num_logits`` for requests verifying ``rows_per_req[i]`` rows each (1: no drafts, e.g. a prefill)."""
+ return torch.tensor([0, *rows_per_req], dtype=torch.int32).cumsum(0)
+
+
def _feed(rec, clock, rounds, num_reqs, count, sampled, period_s, prefill=False):
for _ in range(rounds):
clock.now += period_s
- rec.round(num_reqs, count, prefill, torch.full((num_reqs + 3,), sampled, dtype=torch.int32))
+ rec.round(num_reqs, count, prefill, torch.full((num_reqs + 3,), sampled, dtype=torch.int32), _logits([4] * num_reqs))
def test_rows_are_the_median_period_and_mean_accept_of_steady_rounds(tmp_path):
@@ -40,7 +45,7 @@ def test_a_period_counts_only_between_two_decode_rounds_of_one_shape(tmp_path):
_feed(rec, clock, 3, 8, 15, sampled=5, period_s=0.010) # 2 periods at (8, 16)
_feed(rec, clock, 1, 8, 15, sampled=5, period_s=0.500, prefill=True) # a prefill round: no period
_feed(rec, clock, 1, 8, 15, sampled=5, period_s=0.400) # follows a prefill: no period
- _feed(rec, clock, 1, 9, 15, sampled=5, period_s=0.300) # batch size changed: no period
+ _feed(rec, clock, 1, 9, 15, sampled=5, period_s=0.300) # batch size changed: no period (accept still counts)
_feed(rec, clock, 1, 9, 3, sampled=5, period_s=0.011) # the previous round drafted 15: a width-16 round of 9
_feed(rec, clock, 1, 9, 3, sampled=2, period_s=0.007) # a width-4 round of 9
rows = {(r["batch_size"], r["width"]): r for r in rec.rows()}
@@ -50,6 +55,22 @@ def test_a_period_counts_only_between_two_decode_rounds_of_one_shape(tmp_path):
assert rows[(9, 4)]["round_us"] == 7_000.0 and rows[(9, 4)]["accept"] == 2.0
+def test_accept_is_the_served_mean_over_every_verify_of_the_cell_prefills_included(tmp_path):
+ """A batch that also prefills verifies its drafts as chains and commits fewer tokens; vLLM's spec-decode counters
+ count those rounds, so the cell's accept does too, over the requests that verified drafts only."""
+ clock = Clock()
+ rec = ServedRoundRecorder(str(tmp_path), writer=True, flush_rounds=10_000, min_rounds=1, clock=clock)
+ _feed(rec, clock, 3, 4, 15, sampled=6, period_s=0.010) # 2 tree rounds of 4 requests: 6 tokens each
+ clock.now += 0.050
+ # 4 decode requests verify 16 rows as chains (2 tokens each) beside one new request's prefill (1 row, 1 token)
+ sampled = torch.tensor([2, 2, 2, 2, 1], dtype=torch.int32)
+ rec.round(5, 15, True, sampled, _logits([16, 16, 16, 16, 1]))
+ (row,) = rec.rows()
+ assert (row["batch_size"], row["width"], row["count"]) == (4, 16, 2)
+ assert row["round_us"] == 10_000.0 # the prefill round is not timed
+ assert row["accept"] == round((2 * 4 * 6 + 4 * 2) / (3 * 4), 4) # 56 tokens over 12 request-rounds
+
+
def test_cells_below_min_rounds_are_not_written(tmp_path):
clock = Clock()
rec = ServedRoundRecorder(str(tmp_path), writer=True, flush_rounds=10_000, min_rounds=8, clock=clock)
@@ -61,7 +82,7 @@ def test_flush_merges_into_the_data_path_and_only_the_writer_writes(tmp_path):
clock = Clock()
rec = ServedRoundRecorder(str(tmp_path), writer=True, flush_rounds=4, min_rounds=2, clock=clock)
_feed(rec, clock, 5, 64, 15, sampled=4, period_s=0.048) # the 4th recorded round flushes
- assert load_tree_rounds(str(tmp_path)) == {64: {16: (48_000.0, 4.0)}}
+ assert load_tree_rounds(str(tmp_path)) == {64: {16: (48_000.0, 4.0, 4)}}
other = tmp_path / "other"
quiet = ServedRoundRecorder(str(other), writer=False, flush_rounds=1, min_rounds=1, clock=clock)
_feed(quiet, clock, 3, 64, 15, sampled=4, period_s=0.048)