Skip to content

Official Inference Code of EAGLE-4

feat(tokenspeed): negotiate the plugin contract by capabilities

Seyfal Sultanov6051551cc4a6
diff --git a/docs/compatibility.md b/docs/compatibility.md
index c9ecf65..31aeb6f 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -49,6 +49,13 @@ Each engine process loads the plugin and checks the hooks:
The plugin never raises during loading, so installing eagle-harness cannot break an engine install. Run
`eagle-harness-check` to see the same verdict without starting a server ([Troubleshooting](troubleshooting.md)).
+TokenSpeed admits two plugin contracts. A TokenSpeed that publishes `PLUGIN_CAPABILITIES` must list
+every capability in `REQUIRED_CAPABILITIES` (`eagle_harness/tokenspeed/hooks.py`) and keep the plugin
+API version the adapter was written for. On that line the version changes only for a breaking change. The
+release engine (`0.1.1+eagle.N`) publishes no capabilities and must report plugin API version 4 or
+later. In both cases the adapter then checks the names and parameters of the hooks it calls. The two lines
+name the tree-policy methods the adapter overrides differently, and the adapter overrides both sets.
+
## Structured output on vLLM
Tree-mode batches containing JSON, regex, or forced-tool grammar requests emit only the root token of each verify
diff --git a/docs/configuration.md b/docs/configuration.md
index 598cdcd..634c23b 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -97,8 +97,10 @@ Chains on vLLM: leave the target on vLLM's default attention backend and give on
multi-head EAGLE-4 draft on the 128-token pages a hybrid target needs, and `--attention-backend FLASH_ATTN` moves the
whole target off FlashInfer. Keep the target backend unchanged for a matched speculation comparison.
-TokenSpeed is experimental. It takes the draft shape from its server arguments. `"mode": "static"` is the default and uses every configured
-draft step. `"mode": "serve"` uses calibrated GPU-side decisions to stop drafting and select meaningful verify nodes.
+TokenSpeed is experimental. It takes the draft shape from its server arguments. `"mode": "serve"` is the default, as on
+the other engines: it uses calibrated GPU-side decisions to stop drafting and select meaningful verify nodes, and needs
+`data_path` unless a complete `chain_width_table` (from batch size 1) sets every width. Without a usable config the
+server refuses to start. `"mode": "static"` uses every configured draft step and needs no cost data.
Tree modes keep one physical verify width per server. Serve-mode trees pad unused nodes with unconnected roots.
Pass `--sampling-backend greedy` because the default FlashInfer sampler cannot verify draft trees.
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index c62953b..eb0d7dc 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -46,7 +46,7 @@ no supported host installed (one of: sglang, vllm, tokenspeed)
| `Unknown speculative algorithm name: EAGLE_HARNESS` (sglang), vLLM rejects the method `eagle_harness`, or TokenSpeed does not know the algorithm `EAGLE_HARNESS` | the plugin did not register | run `eagle-harness-check` and read the error the engine logged at startup |
| `EAGLE_HARNESS needs --speculative-algorithm-config (JSON or a path to JSON), ...` | sglang got no config | pass `{}` (live costs), `{"data_path": "<calibration dir>"}` or `{"mode": "static"}` |
| `Cost tables under ... were measured on another setup (stored vs this server): {...}` | `data_path` tables keyed for another GPU, TP size, model pair, engine build or dtype | calibrate for this setup, or drop `data_path` to measure the costs on the served rounds |
-| `EAGLE-Harness mode 'serve' needs data_path (the calibration directory).` | a cost-model mode without cost tables (TokenSpeed) | set `data_path` to matching TokenSpeed costs ([Calibration](calibration.md)); static mode is not a correctness-qualified substitute |
+| `TokenSpeed serve mode (the default) needs data_path or a complete explicit chain schedule ...` | serve mode, set explicitly or by default, with no cost tables and no complete chain schedule (TokenSpeed) | set `data_path` to matching TokenSpeed costs ([Calibration](calibration.md)); static mode is not a correctness-qualified substitute |
| `config: unknown keys ['intensty']; valid keys are [...]` | a misspelt key | use a key from the list ([Configuration](configuration.md)) |
| `mode: 'fast' is not one of static, serve, eval, calibrate.` | a bad value | use one of the listed values |
| `EAGLE_HARNESS needs --speculative-num-steps, --speculative-eagle-topk and --speculative-num-draft-tokens ...` | sglang got no tree shape | pass all three |
diff --git a/eagle_harness/compat.py b/eagle_harness/compat.py
index 18a8742..d100749 100644
--- a/eagle_harness/compat.py
+++ b/eagle_harness/compat.py
@@ -57,7 +57,8 @@ HOSTS = (
Host(
"tokenspeed",
SpecifierSet(">=0.1.1,<0.2"), # = the `tokenspeed` extra in pyproject.toml
- "TokenSpeed 0.1.1+eagle.4 with eagle-harness plugin hooks (see docs/install.md)",
+ "TokenSpeed 0.1.1+eagle.4 (release hooks), or a TokenSpeed with the plugin capabilities in "
+ "eagle_harness.tokenspeed.hooks (see docs/install.md)",
"eagle_harness.tokenspeed.hooks:hook_problems",
),
)
diff --git a/eagle_harness/tokenspeed/__init__.py b/eagle_harness/tokenspeed/__init__.py
index d898f2f..6579b78 100644
--- a/eagle_harness/tokenspeed/__init__.py
+++ b/eagle_harness/tokenspeed/__init__.py
@@ -4,7 +4,8 @@
"""TokenSpeed plugin: EAGLE-Harness as a TokenSpeed drafter.
Registered through the ``tokenspeed.plugins`` entry point (see pyproject.toml) and TokenSpeed's plugin registries, with
-the generic hooks of TokenSpeed branch ``pr-spec-plugin-hooks``; nothing in TokenSpeed is patched.
+the hooks :mod:`eagle_harness.tokenspeed.hooks` checks (the release engine's, or a capability engine's); nothing in
+TokenSpeed is patched.
``docs/architecture.md`` describes the package layout.
"""
diff --git a/eagle_harness/tokenspeed/config.py b/eagle_harness/tokenspeed/config.py
index ae6a416..4b9d5a7 100644
--- a/eagle_harness/tokenspeed/config.py
+++ b/eagle_harness/tokenspeed/config.py
@@ -8,36 +8,39 @@ TokenSpeed hands the parsed JSON object to the drafter (``BaseDrafter.configure_
``--speculative-eagle-topk`` (children per node), ``--speculative-num-steps`` (tree depth) and
``--speculative-num-draft-tokens`` (verify width, root included).
-Static mode keeps a fixed tree. Serve mode uses the calibrated GPU-side policy
-for draft depth and the number of meaningful verify nodes; the physical verify
-window stays fixed and unused slots are unconnected roots.
+Serve mode, the default, uses the calibrated GPU-side policy for draft depth and the number of meaningful verify
+nodes; the physical verify window stays fixed and unused slots are unconnected roots. It needs ``data_path`` unless a
+complete chain schedule sets every width. Static mode (``{"mode": "static"}``) keeps a fixed tree.
"""
from __future__ import annotations
from collections.abc import Mapping
-from dataclasses import dataclass, fields, replace
+from dataclasses import dataclass, fields
from typing import Any
from eagle_harness.core.config import HarnessConfig, Mode, harness_config_from_dict
+from eagle_harness.core.limits import ComputeIntensity
ALGORITHM_NAME = "EAGLE_HARNESS"
+
+
@dataclass(frozen=True)
class TokenSpeedConfig(HarnessConfig):
"""Core policy settings plus an optional explicit per-batch chain schedule."""
chain_width_table: tuple[tuple[int, int], ...] = ()
-
-STATIC = TokenSpeedConfig(mode=Mode.STATIC)
+ @property
+ def fully_scheduled(self) -> bool:
+ """A chain schedule from batch size 1 up: it sets every verify width, so serve mode needs no cost data."""
+ return bool(self.chain_width_table) and self.chain_width_table[0][0] == 1
def parse_algorithm_config(algorithm_config: Mapping[str, Any] | None) -> TokenSpeedConfig:
- """The HarnessConfig of a launch (None: no ``--speculative-algorithm-config``); unknown keys and modes TokenSpeed
- cannot serve raise."""
- if algorithm_config is None:
- return STATIC
- values = dict(algorithm_config)
+ """The TokenSpeedConfig of a launch (None: no ``--speculative-algorithm-config``, read as ``{}``). Serve is the
+ default mode, as in :class:`HarnessConfig`; unknown keys and modes TokenSpeed cannot serve raise."""
+ values = dict(algorithm_config or {})
table = values.pop("chain_width_table", ())
if not isinstance(table, (list, tuple)):
raise ValueError("chain_width_table must contain [minimum batch size, verify width] pairs") # noqa: TRY004 — configuration validation
@@ -52,21 +55,17 @@ def parse_algorithm_config(algorithm_config: Mapping[str, Any] | None) -> TokenS
):
raise ValueError("chain_width_table needs increasing positive batch sizes and verify widths >= 2")
entries.append(tuple(entry))
- fully_scheduled = bool(entries and entries[0][0] == 1 and values.get("mode") == "serve"
- and values.get("intensity") == "chain_intensity")
- # A complete explicit schedule makes no cost decisions and needs no timing files.
- core = harness_config_from_dict({**values, "mode": "static"} if fully_scheduled else values)
- if fully_scheduled:
- core = replace(core, mode=Mode.SERVE)
- if core.mode is Mode.SERVE and not fully_scheduled and not core.data_path:
- raise ValueError("TokenSpeed serve mode needs data_path or a complete explicit chain schedule; live costs are unsupported")
+ core = harness_config_from_dict(values)
config = TokenSpeedConfig(**{field.name: getattr(core, field.name) for field in fields(core)},
chain_width_table=tuple(entries))
- if entries:
- from eagle_harness.core.limits import ComputeIntensity
-
- if config.intensity is not ComputeIntensity.CHAIN or config.mode is not Mode.SERVE:
- raise ValueError("chain_width_table requires serve mode and chain_intensity")
if config.mode not in (Mode.STATIC, Mode.SERVE):
raise NotImplementedError(f"{ALGORITHM_NAME} on TokenSpeed supports static and serve modes")
+ if entries and (config.intensity is not ComputeIntensity.CHAIN or config.mode is not Mode.SERVE):
+ raise ValueError("chain_width_table requires serve mode and chain_intensity")
+ if config.mode is Mode.SERVE and not config.fully_scheduled and not config.data_path:
+ raise ValueError(
+ "TokenSpeed serve mode (the default) needs data_path or a complete explicit chain schedule "
+ '(chain_intensity with a chain_width_table from batch size 1); live costs are unsupported. '
+ 'Pass {"mode": "static"} for a fixed tree.'
+ )
return config
diff --git a/eagle_harness/tokenspeed/drafter.py b/eagle_harness/tokenspeed/drafter.py
index d43edc9..73b5d4d 100644
--- a/eagle_harness/tokenspeed/drafter.py
+++ b/eagle_harness/tokenspeed/drafter.py
@@ -35,10 +35,16 @@ from typing_extensions import override
from eagle_harness.core.config import DraftFamily, Mode, build_cost_model
from eagle_harness.core.draft_tree import DraftTree, TreeShape
from eagle_harness.core.limits import ComputeIntensity
-from eagle_harness.tokenspeed.config import ALGORITHM_NAME, STATIC, TokenSpeedConfig, parse_algorithm_config
+from eagle_harness.core.models import target_is_moe
+from eagle_harness.tokenspeed.config import ALGORITHM_NAME, TokenSpeedConfig, parse_algorithm_config
from eagle_harness.tokenspeed.costs import tree_policy_costs
+from eagle_harness.tokenspeed.hooks import tree_policy
from eagle_harness.tokenspeed.models import CandidateRows, LlamaForCausalLMEagle4
-from eagle_harness.tokenspeed.tree_lanes import advance_lane_masks, lane_bits, seed_lane_masks, verify_window
+from eagle_harness.tokenspeed.tree_lanes import advance_lane_masks, lane_bits, seed_lane_masks
+from eagle_harness.tokenspeed.tree_lanes import verify_window as fill_verify_window
+
+# TokenSpeed's own candidate ranking, under the installed engine's name (see hooks.tree_policy).
+_ENGINE_CANDIDATES = getattr(DynamicDrafter, tree_policy().candidates)
class HarnessDrafter(DynamicDrafter):
@@ -50,7 +56,7 @@ class HarnessDrafter(DynamicDrafter):
if not isinstance(model, LlamaForCausalLMEagle3):
raise TypeError(f"{ALGORITHM_NAME} requires an EAGLE-3 or EAGLE-4 draft, got {type(model)}")
self.draft_model = model
- self.config: TokenSpeedConfig = STATIC
+ self.config: TokenSpeedConfig | None = None # set by configure_algorithm, else resolved in bind_tree
self.tree: DraftTree | None = None
self._lane_bits: torch.Tensor | None = None
@@ -64,18 +70,14 @@ class HarnessDrafter(DynamicDrafter):
@override
def wire_target(self, target: Any) -> None:
super().wire_target(target)
- expert_counts = (
- getattr(target.config, name, 0) for name in ("num_experts", "num_local_experts", "n_routed_experts")
- )
- self._target_is_moe = any(expert_counts)
+ self._target_is_moe = target_is_moe(target.config)
@property
def dynamic(self) -> bool:
- return self.config.mode is Mode.SERVE
+ return self.config is not None and self.config.mode is Mode.SERVE
def _make_policy(self, verify_num: int, topk: int, depth: int) -> DevicePolicy:
- fully_scheduled = bool(self.config.chain_width_table and self.config.chain_width_table[0][0] == 1)
- model = None if fully_scheduled else build_cost_model(
+ model = None if self.config.fully_scheduled else build_cost_model(
self.config,
node_top_k=topk,
tree_depth=depth,
@@ -99,6 +101,8 @@ class HarnessDrafter(DynamicDrafter):
@override
def bind_tree(self, tree_spec: Any) -> None:
+ if self.config is None: # launched without --speculative-algorithm-config: the defaults, or their refusal
+ self.config = parse_algorithm_config(None)
if self.dynamic:
shape = tree_spec.config
self.bind_dynamic_tree(tree_spec, self._make_policy(shape.num_nodes, shape.topk, shape.num_steps))
@@ -141,7 +145,9 @@ class HarnessDrafter(DynamicDrafter):
return super().run(base_ctx, logits_output, output_tokens, accept_lengths)
# ------------------------------------------------------------------ the tree policy
- def _candidates(self, rows: CandidateRows) -> tuple[torch.Tensor, torch.Tensor]:
+ # Defined under TokenSpeed's public names (hooks.PUBLIC_POLICY) and aliased to the release engine's private ones
+ # at the end of the class; each engine calls only its own names.
+ def round_candidates(self, rows: CandidateRows) -> tuple[torch.Tensor, torch.Tensor]:
if isinstance(self.draft_model, LlamaForCausalLMEagle4):
if self.sampled_trees:
rows.next_token_logits, rows.candidate_ids, topk = self.draft_model.candidate_head(
@@ -149,24 +155,22 @@ class HarnessDrafter(DynamicDrafter):
)
return topk
return self.draft_model.candidate_topk(rows.normed, self.lanes_per_request)
- return super()._candidates(rows)
+ return _ENGINE_CANDIDATES(self, rows)
- @override
- def _seed_tree_lanes(self, bs: int, logits_output: CandidateRows, frontier: torch.Tensor):
+ def seed_tree(self, bs: int, logits_output: CandidateRows, frontier: torch.Tensor):
"""Depth 1 from the draft extend's candidates; returns the lanes' ``[bs, K]`` tokens and ``[bs * K, H]`` rows."""
tree, k = self.tree, self.lanes_per_request
- probs, tokens = self._candidates(logits_output)
+ probs, tokens = self.round_candidates(logits_output)
tree.stage_root(bs, probs, tokens, logits_output.hidden_states)
tree.begin(bs)
seed_lane_masks(self.tree_lanes.lane_mask, bs, self._lane_bits)
self.tree_lanes.set_frontier(bs, frontier)
return tree.front_tokens[: bs * k].view(bs, k), tree.front_hidden[: bs * k]
- @override
- def _expand_tree_lanes(self, bs: int, step: int, logits_output: CandidateRows):
+ def expand_tree(self, bs: int, step: int, logits_output: CandidateRows):
"""Children of the depth-``step`` lanes; returns the next lanes' tokens and rows (``None`` after the last step)."""
tree, k = self.tree, self.lanes_per_request
- probs, tokens = self._candidates(logits_output)
+ probs, tokens = self.round_candidates(logits_output)
tree.step(bs, step, probs, tokens, logits_output.hidden_states)
lanes = tree.front_tokens[: bs * k].view(bs, k)
if step == self.spec_num_steps - 1:
@@ -174,10 +178,15 @@ class HarnessDrafter(DynamicDrafter):
advance_lane_masks(tree, self.tree_lanes.lane_mask, bs, step, self._lane_bits)
return lanes, tree.front_hidden[: bs * k]
- @override
- def _draft_window(self, bs: int, next_tokens: torch.Tensor) -> torch.Tensor:
+ def verify_window(self, bs: int, next_tokens: torch.Tensor) -> torch.Tensor:
"""The best ``N - 1`` nodes and the root as next round's verify window; their parents into the tree spec."""
- verify_window(
+ fill_verify_window(
self.tree, bs, self.spec_num_steps, next_tokens[:, 0], next_tokens, self.tree_spec.draft_parent_buf[:bs]
)
return next_tokens
+
+ # The release engine's names for the same policy (hooks.RELEASE_POLICY).
+ _candidates = round_candidates
+ _seed_tree_lanes = seed_tree
+ _expand_tree_lanes = expand_tree
+ _draft_window = verify_window
diff --git a/eagle_harness/tokenspeed/hooks.py b/eagle_harness/tokenspeed/hooks.py
index 6470b02..55626da 100644
--- a/eagle_harness/tokenspeed/hooks.py
+++ b/eagle_harness/tokenspeed/hooks.py
@@ -7,15 +7,20 @@
(:func:`eagle_harness.tokenspeed.plugin.register`) and ``eagle-harness-check`` reports it, so a TokenSpeed refactor that
drops or renames a hook fails at load time instead of in a GPU run.
-Three groups:
-
-- the plugin API of TokenSpeed main (``tokenspeed.plugins`` entry points, the drafter and model registries);
-- the generic hooks of TokenSpeed branch ``pr-spec-plugin-hooks`` (``pr/TOKENSPEED_HOOKS.md``): H1 the algorithm config, H2 the
- target's aux hidden states for a plugin algorithm, H3 tree drafting by a plugin drafter, and the sliding-window
- attention of tree lanes (the EAGLE-4 draft layer has a window; TokenSpeed main refuses it in a tree);
-- the tree policy of TokenSpeed's ``Eagle`` drafter that :class:`~eagle_harness.tokenspeed.drafter.HarnessDrafter`
- replaces (seed, expand, finalize of the draft tree). These are not public API yet: the check pins their names and
- parameters so a change shows up here first.
+Two TokenSpeed lines carry the hooks, told apart by :func:`contract`:
+
+- ``capabilities``: TokenSpeed advertises ``PLUGIN_CAPABILITIES``, one name per additive plugin contract, and bumps
+ ``PLUGIN_API_VERSION`` only for a breaking change. The adapter requires :data:`REQUIRED_CAPABILITIES` and an API
+ version in :data:`CAPABILITY_API_VERSIONS`, then pins the names it calls. ``Eagle``'s tree policy is public there
+ (:data:`PUBLIC_POLICY`).
+- ``release``: the eagle-harness release engine (TokenSpeed ``0.1.1+eagle.N``) has no capability set; its
+ ``PLUGIN_API_VERSION`` (at least :data:`RELEASE_MIN_API_VERSION`) counts every contract, and the tree policy has the
+ private names of :data:`RELEASE_POLICY`.
+
+On both, the adapter needs the plugin registries, the algorithm config and the target's aux hidden states for a plugin
+algorithm, tree layout for a plugin chain, sliding-window tree lanes (the EAGLE-4 draft layer has a window), the
+drafter round protocol and tree lanes, the tree policy of TokenSpeed's ``Eagle`` drafter that
+:class:`~eagle_harness.tokenspeed.drafter.HarnessDrafter` replaces, and the dynamic tree with its device policy.
"""
from __future__ import annotations
@@ -24,7 +29,21 @@ import importlib
import inspect
from typing import NamedTuple
-MIN_PLUGIN_API_VERSION = 4
+RELEASE_MIN_API_VERSION = 4
+CAPABILITY_API_VERSIONS = frozenset({3})
+REQUIRED_CAPABILITIES = frozenset(
+ {
+ "drafter.algorithm_config",
+ "drafter.aux_hidden_capture",
+ "drafter.tree_layout",
+ "attention.windowed_tree_lanes",
+ "drafter.round_protocol",
+ "drafter.tree_lanes",
+ "drafter.tree_policy",
+ "drafter.dynamic_tree",
+ "drafter.sampled_trees",
+ }
+)
class Hook(NamedTuple):
@@ -32,6 +51,31 @@ class Hook(NamedTuple):
params: tuple[str, ...] = () # parameter names the callable must accept
+class TreePolicy(NamedTuple):
+ """The names of the tree-policy methods :class:`~eagle_harness.tokenspeed.drafter.HarnessDrafter` overrides."""
+
+ candidates: str # DynamicDrafter: each draft row's best K candidates
+ seed: str # Eagle: the first lanes
+ expand: str # Eagle: the next lanes
+ window: str # Eagle: the next verify window and its parents
+
+
+PUBLIC_POLICY = TreePolicy("round_candidates", "seed_tree", "expand_tree", "verify_window")
+RELEASE_POLICY = TreePolicy("_candidates", "_seed_tree_lanes", "_expand_tree_lanes", "_draft_window")
+
+_DYNAMIC = "tokenspeed.runtime.execution.drafter.tree_round.dynamic:DynamicDrafter"
+_EAGLE = "tokenspeed.runtime.execution.drafter.eagle:Eagle"
+
+
+def _policy_hooks(names: TreePolicy) -> tuple[Hook, ...]:
+ return (
+ Hook(f"{_DYNAMIC}.{names.candidates}", ("logits_output",)),
+ Hook(f"{_EAGLE}.{names.seed}", ("bs", "logits_output", "frontier")),
+ Hook(f"{_EAGLE}.{names.expand}", ("bs", "step", "logits_output")),
+ Hook(f"{_EAGLE}.{names.window}", ("bs", "next_tokens")),
+ )
+
+
HOOKS: tuple[Hook, ...] = (
Hook("tokenspeed.runtime.plugins:PLUGIN_API_VERSION"),
Hook(
@@ -40,14 +84,12 @@ HOOKS: tuple[Hook, ...] = (
),
Hook("tokenspeed.runtime.plugins.registry:register_model", ("cls", "architectures")),
Hook("tokenspeed.runtime.configs.model_profile:ModelProfile"),
- Hook("tokenspeed.runtime.execution.drafter.base:BaseDrafter.configure_algorithm", ("algorithm_config",)), # H1
- Hook("tokenspeed.runtime.execution.drafter:drafter_captures_aux_hidden_states", ("algorithm",)), # H2
- Hook("tokenspeed.runtime.execution.drafter.eagle:Eagle.bind_tree", ("tree_spec",)),
- Hook("tokenspeed.runtime.execution.drafter.eagle:Eagle.bind_tree_lanes", ("tree_spec",)),
- Hook(
- "tokenspeed.runtime.execution.drafter.tree_round.dynamic:DynamicDrafter.bind_dynamic_tree",
- ("tree_spec", "policy"),
- ),
+ Hook("tokenspeed.runtime.execution.drafter.base:BaseDrafter.configure_algorithm", ("algorithm_config",)),
+ Hook("tokenspeed.runtime.execution.drafter:drafter_captures_aux_hidden_states", ("algorithm",)),
+ Hook(f"{_EAGLE}.bind_tree", ("tree_spec",)),
+ Hook(f"{_EAGLE}.bind_tree_lanes", ("tree_spec",)),
+ Hook(f"{_DYNAMIC}.bind_dynamic_tree", ("tree_spec", "policy")),
+ Hook(f"{_DYNAMIC}.enable_sampled_trees", ("num_candidates", "seed")),
Hook("tokenspeed.runtime.execution.drafter.tree_round.device_policy:DevicePolicy", ("costs", "device")),
Hook("tokenspeed.runtime.execution.drafter.base:BaseDrafter.replay_decode_graph", ("graph", "bs", "graph_bs")),
Hook("tokenspeed.runtime.execution.drafter.base:BaseDrafter.finish_round", ("ctx", "graph_bs")),
@@ -58,31 +100,59 @@ HOOKS: tuple[Hook, ...] = (
),
Hook("tokenspeed.runtime.execution.drafter.base:BaseDrafter.has_round_graphs", ("graph_bs",)),
Hook("tokenspeed.runtime.execution.drafter.base:BaseDrafter.release_round_graphs", ()),
- Hook("tokenspeed.runtime.execution.drafter.eagle:Eagle._seed_tree_lanes", ("bs", "logits_output", "frontier")),
- Hook("tokenspeed.runtime.execution.drafter.eagle:Eagle._expand_tree_lanes", ("bs", "step", "logits_output")),
- Hook("tokenspeed.runtime.execution.drafter.eagle:Eagle._draft_window", ("bs", "next_tokens")),
Hook("tokenspeed.runtime.layers.attention.backends.base:AttentionBackend.begin_tree_lanes", ("bs", "live_bs")),
Hook("tokenspeed.runtime.layers.attention.backends.paged.tree_verify:TreeDraftInputs.set_frontier"),
- # the EAGLE-4 draft layer has a sliding window: tree lanes need the hooks branch's sliding-window lane attention
+ Hook("tokenspeed.runtime.models.llama_eagle3:LlamaForCausalLMEagle3.exit_logits"),
+ Hook("tokenspeed.runtime.execution.context:ForwardContext.gather_ids"),
+ Hook("tokenspeed.runtime.distributed.comm_ops:all_gather", ("tensor", "group", "dim")),
+)
+CAPABILITY_HOOKS: tuple[Hook, ...] = _policy_hooks(PUBLIC_POLICY)
+RELEASE_HOOKS: tuple[Hook, ...] = (
+ *_policy_hooks(RELEASE_POLICY),
+ # the release engine names no capability for the sliding-window lane attention the EAGLE-4 draft layer needs
Hook(
"tokenspeed.runtime.layers.attention.backends.paged.trtllm:TRTLLMMHAAttnBackend._tree_lane_window_cascade",
("lanes", "step"),
),
- Hook("tokenspeed.runtime.models.llama_eagle3:LlamaForCausalLMEagle3.exit_logits"),
- Hook("tokenspeed.runtime.execution.context:ForwardContext.gather_ids"),
- Hook("tokenspeed.runtime.distributed.comm_ops:all_gather", ("tensor", "group", "dim")),
)
+def contract() -> str | None:
+ """``"capabilities"``, ``"release"``, or None when TokenSpeed has no plugin API."""
+ try:
+ plugins = importlib.import_module("tokenspeed.runtime.plugins")
+ except ImportError:
+ return None
+ return "capabilities" if hasattr(plugins, "PLUGIN_CAPABILITIES") else "release"
+
+
+def tree_policy() -> TreePolicy:
+ """The tree-policy names of the installed TokenSpeed (the public ones when it has neither)."""
+ return RELEASE_POLICY if contract() == "release" else PUBLIC_POLICY
+
+
def hook_problems() -> list[str]:
- """What this TokenSpeed lacks of :data:`HOOKS` (empty: every hook the adapter uses is there)."""
- problems = [_problem(hook) for hook in HOOKS]
- problems = [p for p in problems if p]
- if not problems:
+ """What this TokenSpeed lacks of the adapter's contract (empty: every hook the adapter uses is there)."""
+ kind = contract()
+ problems: list[str] = []
+ if kind == "capabilities":
+ from tokenspeed.runtime.plugins import PLUGIN_API_VERSION, PLUGIN_CAPABILITIES
+
+ if PLUGIN_API_VERSION not in CAPABILITY_API_VERSIONS:
+ problems.append(
+ f"PLUGIN_API_VERSION {PLUGIN_API_VERSION} is not one of {sorted(CAPABILITY_API_VERSIONS)} "
+ "(a breaking plugin API change)"
+ )
+ missing = sorted(REQUIRED_CAPABILITIES - set(PLUGIN_CAPABILITIES))
+ if missing:
+ problems.append(f"PLUGIN_CAPABILITIES lacks {', '.join(missing)}")
+ hooks = HOOKS + (CAPABILITY_HOOKS if kind == "capabilities" else RELEASE_HOOKS)
+ problems += [p for p in map(_problem, hooks) if p]
+ if not problems and kind == "release":
from tokenspeed.runtime.plugins import PLUGIN_API_VERSION
- if PLUGIN_API_VERSION < MIN_PLUGIN_API_VERSION:
- problems.append(f"PLUGIN_API_VERSION {PLUGIN_API_VERSION} < {MIN_PLUGIN_API_VERSION}")
+ if PLUGIN_API_VERSION < RELEASE_MIN_API_VERSION:
+ problems.append(f"PLUGIN_API_VERSION {PLUGIN_API_VERSION} < {RELEASE_MIN_API_VERSION}")
return problems
diff --git a/tests/test_tokenspeed_adapter.py b/tests/test_tokenspeed_adapter.py
index 7852a38..9fa976c 100644
--- a/tests/test_tokenspeed_adapter.py
+++ b/tests/test_tokenspeed_adapter.py
@@ -31,8 +31,16 @@ K, STEPS, H, BS, WIDTH = 4, 5, 8, 3, 16
# ------------------------------------------------------------------ config
-def test_no_config_is_a_static_tree():
- assert parse_algorithm_config(None).mode is Mode.STATIC
[email protected]("algorithm_config", [None, {}])
+def test_serve_is_the_default_and_needs_costs(algorithm_config):
+ # The same default as a config that omits "mode": serve, which refuses to run without its cost inputs.
+ with pytest.raises(ValueError, match=r"serve mode \(the default\) needs data_path.*\"mode\": \"static\""):
+ parse_algorithm_config(algorithm_config)
+ assert parse_algorithm_config({"data_path": "/calibration"}).mode is Mode.SERVE
+
+
+def test_static_is_chosen_explicitly():
+ assert parse_algorithm_config({"mode": "static"}).mode is Mode.STATIC
def test_static_config_parses_harness_keys():
@@ -93,6 +101,21 @@ def test_tree_mode_rejects_chain_width_schedule():
})
[email protected]("mode", [{}, {"mode": "serve"}])
+def test_complete_chain_schedule_needs_no_mode_and_no_calibration(mode):
+ # Serve is the default, so a complete schedule without "mode" is the same launch as one with it.
+ config = parse_algorithm_config({"intensity": "chain_intensity", "chain_width_table": [[1, 4], [32, 2]], **mode})
+ assert config.mode is Mode.SERVE and not config.data_path and config.fully_scheduled
+
+
+def test_only_a_schedule_from_batch_size_one_is_complete():
+ config = parse_algorithm_config({
+ "data_path": "/calibration", "intensity": "chain_intensity", "chain_width_table": [[2, 4], [32, 2]],
+ })
+ assert not config.fully_scheduled
+ assert not parse_algorithm_config({"data_path": "/calibration"}).fully_scheduled
+
+
def test_complete_chain_schedule_needs_no_calibration():
config = parse_algorithm_config({
"mode": "serve", "intensity": "chain_intensity", "chain_width_table": [[1, 8], [64, 4]],
@@ -153,6 +176,76 @@ def test_hook_check_names_what_is_missing(fake_host):
assert "not importable" in hooks._problem(hooks.Hook("nosuchhost.api:x"))
+def fake_plugins(monkeypatch):
+ """A ``tokenspeed.runtime.plugins`` module whose every pinned hook resolves; returns it for the test to shape."""
+ packages = {name: types.ModuleType(name) for name in ("tokenspeed", "tokenspeed.runtime")}
+ plugins = types.ModuleType("tokenspeed.runtime.plugins")
+ for name, module in {**packages, plugins.__name__: plugins}.items():
+ monkeypatch.setitem(sys.modules, name, module)
+ monkeypatch.setattr(hooks, "_problem", lambda hook: None)
+ return plugins
+
+
+def test_capability_contract_registers_with_every_capability(fake_plugins):
+ fake_plugins.PLUGIN_API_VERSION = 3
+ fake_plugins.PLUGIN_CAPABILITIES = hooks.REQUIRED_CAPABILITIES | {"drafter.suspend_drafting"}
+ assert hooks.contract() == "capabilities"
+ assert hooks.hook_problems() == []
+ assert hooks.tree_policy() == hooks.PUBLIC_POLICY
+
+
+def test_capability_contract_names_a_missing_capability(fake_plugins):
+ fake_plugins.PLUGIN_API_VERSION = 3
+ fake_plugins.PLUGIN_CAPABILITIES = hooks.REQUIRED_CAPABILITIES - {"drafter.dynamic_tree"}
+ assert hooks.hook_problems() == ["PLUGIN_CAPABILITIES lacks drafter.dynamic_tree"]
+
+
+def test_capability_contract_refuses_a_breaking_api_version(fake_plugins):
+ # A capability engine's version counts breaking changes only: a higher one is not "newer and compatible".
+ fake_plugins.PLUGIN_API_VERSION = 4
+ fake_plugins.PLUGIN_CAPABILITIES = hooks.REQUIRED_CAPABILITIES
+ (problem,) = hooks.hook_problems()
+ assert "PLUGIN_API_VERSION 4" in problem and "breaking" in problem
+
+
+def test_release_contract_takes_the_release_names(fake_plugins):
+ fake_plugins.PLUGIN_API_VERSION = 4
+ assert hooks.contract() == "release"
+ assert hooks.hook_problems() == []
+ assert hooks.tree_policy() == hooks.RELEASE_POLICY
+
+
+def test_release_contract_refuses_an_older_api_version(fake_plugins):
+ # Without capabilities, version 3 is the plugin API of TokenSpeed main before the eagle-harness hooks.
+ fake_plugins.PLUGIN_API_VERSION = 3
+ assert hooks.hook_problems() == ["PLUGIN_API_VERSION 3 < 4"]
+
+
+def test_each_contract_pins_its_own_tree_policy_names():
+ capability = {h.path.rpartition(".")[2] for h in hooks.CAPABILITY_HOOKS}
+ release = {h.path.rpartition(".")[2] for h in hooks.RELEASE_HOOKS}
+ assert set(hooks.PUBLIC_POLICY) <= capability and not set(hooks.RELEASE_POLICY) & capability
+ assert set(hooks.RELEASE_POLICY) <= release and not set(hooks.PUBLIC_POLICY) & release
+
+
+def test_the_drafter_aliases_every_release_name_to_its_public_policy():
+ # drafter.py imports TokenSpeed, so read its class body instead of importing it.
+ import ast
+ from pathlib import Path
+
+ tree = ast.parse(Path(hooks.__file__).with_name("drafter.py").read_text())
+ (cls,) = [node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "HarnessDrafter"]
+ methods = {node.name for node in cls.body if isinstance(node, ast.FunctionDef)}
+ aliases = {
+ node.targets[0].id: node.value.id
+ for node in cls.body
+ if isinstance(node, ast.Assign) and isinstance(node.value, ast.Name)
+ }
+ assert set(hooks.PUBLIC_POLICY) <= methods
+ assert aliases == dict(zip(hooks.RELEASE_POLICY, hooks.PUBLIC_POLICY))
+
+
# ------------------------------------------------------------------ the tree as TokenSpeed lanes
def _drafted(seed=0):
"""A tree grown as HarnessDrafter grows it, with TokenSpeed's lane masks, plus each node's parent node and the
diff --git a/tests/test_tokenspeed_plugin.py b/tests/test_tokenspeed_plugin.py
index 607216f..923c96b 100755
--- a/tests/test_tokenspeed_plugin.py
+++ b/tests/test_tokenspeed_plugin.py
@@ -4,8 +4,8 @@
"""The TokenSpeed plugin against the installed TokenSpeed: hook check, registration, the draft model's profile.
No GPU work, but TokenSpeed imports only on a host with a GPU (its kernel package refuses otherwise), so this runs in
-the GPU test jobs and is skipped elsewhere. On a TokenSpeed without the ``pr-spec-plugin-hooks`` hooks the registration tests
-check that the plugin switches itself off instead.
+the GPU test jobs and is skipped elsewhere. On a TokenSpeed without the adapter's hooks (:mod:`eagle_harness.tokenspeed.hooks`: the release engine or a
+capability engine) the registration tests check that the plugin switches itself off instead.
"""
from __future__ import annotations
@@ -32,7 +32,7 @@ from eagle_harness.tokenspeed.hooks import hook_problems # noqa: E402
HAS_HOOKS = not hook_problems()
needs_hooks = pytest.mark.skipif(
- not HAS_HOOKS, reason=f"TokenSpeed without the pr-spec-plugin-hooks hooks: {hook_problems()}"
+ not HAS_HOOKS, reason=f"TokenSpeed without the adapter's hooks: {hook_problems()}"
)
@@ -72,6 +72,38 @@ def test_draft_profile_is_a_valid_mha_profile():
assert isinstance(profile, ModelProfile) and profile.cache_family == "mha" and profile.linear_attention is None
+@needs_hooks
+def test_the_engine_calls_the_harness_tree_policy():
+ # HarnessDrafter defines the public names and aliases the release ones; the installed engine must call one set.
+ from tokenspeed.runtime.execution.drafter.eagle import Eagle
+ from tokenspeed.runtime.execution.drafter.tree_round.dynamic import DynamicDrafter
+
+ from eagle_harness.tokenspeed.drafter import HarnessDrafter
+ from eagle_harness.tokenspeed.hooks import PUBLIC_POLICY, RELEASE_POLICY, tree_policy
+
+ names = tree_policy()
+ for public, release in zip(PUBLIC_POLICY, RELEASE_POLICY):
+ assert getattr(HarnessDrafter, release) is getattr(HarnessDrafter, public)
+ assert hasattr(DynamicDrafter, names.candidates)
+ for name in names[1:]:
+ assert getattr(HarnessDrafter, name) is not getattr(Eagle, name)
+
+
+@needs_hooks
+def test_a_wrapped_moe_target_is_moe(monkeypatch):
+ # Experts under text_config (a multimodal wrapper) count, as in core.models.target_is_moe.
+ from types import SimpleNamespace
+
+ from tokenspeed.runtime.execution.drafter.tree_round.dynamic import DynamicDrafter
+
+ from eagle_harness.tokenspeed.drafter import HarnessDrafter
+
+ monkeypatch.setattr(DynamicDrafter, "wire_target", lambda self, target: None)
+ drafter = HarnessDrafter.__new__(HarnessDrafter)
+ drafter.wire_target(SimpleNamespace(config=SimpleNamespace(text_config=SimpleNamespace(num_experts=64))))
+ assert drafter._target_is_moe is True
+
+
@needs_hooks
def test_compat_reports_the_hooks_ok():
assert compat.check("tokenspeed").ok