Skip to content

Official Inference Code of EAGLE-4

fix(sglang): accept the review hooks' msgspec accept types and moved kv-indices kernel

Seyfal Sultanov88baf1eaf191
diff --git a/eagle_harness/sglang/hooks.py b/eagle_harness/sglang/hooks.py
index 80f04ba..7c1bb38 100644
--- a/eagle_harness/sglang/hooks.py
+++ b/eagle_harness/sglang/hooks.py
@@ -7,7 +7,8 @@ Each :class:`Hook` names an sglang attribute and the parameters the plugin expec
- ``override``: the plugin overrides it, so the parameter names must match exactly (a parameter sglang adds would
never reach the override);
-- ``call``: the plugin calls it, so the expected names must be among sglang's (sglang may add optional ones);
+- ``call``: the plugin calls it, so the expected names must be among sglang's (sglang may add optional ones); a
+ class means its constructor, whether sglang declares it a dataclass or a ``msgspec.Struct``;
- ``field``: a field of an sglang argument group (``get_spec()`` and friends) or data class, or a class-level
default the plugin's subclass sets.
@@ -146,8 +147,8 @@ HOOKS: tuple[Hook, ...] = (
_RUN_VERIFY,
CALL,
),
- Hook("sglang.srt.speculative.eagle_worker_common:VerifyAcceptInput.__init__", _ACCEPT_INPUT, CALL),
- Hook("sglang.srt.speculative.eagle_worker_common:VerifyAcceptResult.__init__", _ACCEPT_RESULT, CALL),
+ Hook("sglang.srt.speculative.eagle_worker_common:VerifyAcceptInput", _ACCEPT_INPUT, CALL),
+ Hook("sglang.srt.speculative.eagle_worker_common:VerifyAcceptResult", _ACCEPT_RESULT, CALL),
# The EAGLE V2 worker the cost-model worker extends (prefill, pools, backends stay sglang's).
Hook(f"{_WORKER}.__init__", ("server_args", "gpu_id", "nccl_port", "target_worker"), CALL),
Hook(
@@ -179,8 +180,24 @@ def resolve(path: str):
return obj
+def first_present(*paths: str):
+ """The object at the first of ``paths`` the installed sglang has (for a name sglang has moved)."""
+ for path in paths:
+ try:
+ return resolve(path)
+ except (ImportError, AttributeError):
+ continue
+ raise ImportError(f"sglang has none of {', '.join(paths)}")
+
+
+def field_names(cls) -> tuple[str, ...]:
+ """The fields of a dataclass or ``msgspec.Struct`` (empty for other classes)."""
+ return (*getattr(cls, "__struct_fields__", ()), *getattr(cls, "__dataclass_fields__", ()))
+
+
def parameter_names(func) -> tuple[str, ...]:
- """Parameter names of ``func`` after ``self`` / ``cls`` (``*args`` / ``**kwargs`` excluded)."""
+ """Parameter names of ``func`` after ``self`` / ``cls`` (``*args`` / ``**kwargs`` excluded); for a class, of
+ its constructor."""
params = [
p
for p in inspect.signature(func).parameters.values()
@@ -196,7 +213,7 @@ def _problem(hook: Hook) -> str | None:
cls_path, _, name = hook.path.rpartition(".")
try:
cls = resolve(cls_path)
- fields = (*getattr(cls, "__struct_fields__", ()), *getattr(cls, "__dataclass_fields__", ()))
+ fields = field_names(cls)
except (ImportError, AttributeError):
return f"{cls_path} is missing"
return None if name in fields or name in vars(cls) else f"{hook.path} is missing"
diff --git a/eagle_harness/sglang/verify_input.py b/eagle_harness/sglang/verify_input.py
index f65a404..982edd5 100644
--- a/eagle_harness/sglang/verify_input.py
+++ b/eagle_harness/sglang/verify_input.py
@@ -17,10 +17,11 @@ from typing import TYPE_CHECKING, Optional, Tuple
import torch
-from sglang.kernels.ops.attention.utils import create_flashinfer_kv_indices_triton
from sglang.srt.mem_cache.kv_loc_plan import IdSpaceKind
from sglang.srt.speculative.eagle_info import EagleVerifyInput
+from eagle_harness.sglang.hooks import first_present
+
if TYPE_CHECKING:
from sglang.srt.mem_cache.kv_index_translator import KVIndexTranslator
from sglang.srt.mem_cache.kv_loc_plan import KVLocPlan
@@ -28,6 +29,12 @@ if TYPE_CHECKING:
from eagle_harness.sglang.verify_plan import TreeTailMask
+# sglang main keeps the kernel in its own module; the eagle/v1 release re-exports it from the attention utils.
+create_flashinfer_kv_indices_triton = first_present(
+ "sglang.kernels.ops.attention.kv_indices:create_flashinfer_kv_indices_triton",
+ "sglang.kernels.ops.attention.utils:create_flashinfer_kv_indices_triton",
+)
+
def build_attn_args(
req_to_token: torch.Tensor,
diff --git a/tests/test_sglang_hooks.py b/tests/test_sglang_hooks.py
index 4dbd2e9..cf6758b 100644
--- a/tests/test_sglang_hooks.py
+++ b/tests/test_sglang_hooks.py
@@ -104,3 +104,69 @@ def test_register_on_a_matching_sglang(clean_registry):
assert plugin.register() is True
assert plugin.register() is True # idempotent
assert SpeculativeAlgorithm.from_string(ALGORITHM_NAME).is_eagle()
+
+
+def _fake_module(monkeypatch, name, **attrs):
+ import sys
+ import types
+
+ module = types.ModuleType(name)
+ module.__dict__.update(attrs)
+ monkeypatch.setitem(sys.modules, name, module)
+ return module
+
+
[email protected]("shape", ["dataclass", "msgspec"])
+def test_a_constructed_type_is_checked_by_its_fields(monkeypatch, shape):
+ """sglang declares the accept step's input/result as dataclasses (eagle/v1) or ``msgspec.Struct`` (main)."""
+ if shape == "dataclass":
+ import dataclasses
+
+ @dataclasses.dataclass(frozen=True)
+ class Result:
+ next_token_ids: int
+ accept_lens: int
+ hidden_states: object = None
+
+ else:
+ msgspec = pytest.importorskip("msgspec")
+
+ class Result(msgspec.Struct, frozen=True):
+ next_token_ids: int
+ accept_lens: int
+ hidden_states: object = None
+
+ _fake_module(monkeypatch, "fake_sglang_types", Result=Result)
+ assert hooks.field_names(Result) == ("next_token_ids", "accept_lens", "hidden_states")
+ monkeypatch.setattr(
+ hooks,
+ "HOOKS",
+ (
+ hooks.Hook("fake_sglang_types:Result", ("next_token_ids", "accept_lens"), hooks.CALL),
+ hooks.Hook("fake_sglang_types:Result", ("next_token_ids", "bonus_tokens"), hooks.CALL),
+ hooks.Hook("fake_sglang_types:Result.accept_lens", (), hooks.FIELD),
+ ),
+ )
+ assert hooks.hook_problems() == [
+ "fake_sglang_types:Result('next_token_ids', 'accept_lens', 'hidden_states') lacks ('bonus_tokens',)"
+ ]
+
+
+def test_first_present_takes_the_first_location_sglang_has(monkeypatch):
+ """A kernel sglang moved (create_flashinfer_kv_indices_triton) resolves at its new or its old home."""
+ _fake_module(monkeypatch, "fake_sglang_old", kernel="old")
+ _fake_module(monkeypatch, "fake_sglang_new", kernel="new")
+ assert hooks.first_present("fake_sglang_new:kernel", "fake_sglang_old:kernel") == "new"
+ assert hooks.first_present("fake_sglang_gone:kernel", "fake_sglang_old:kernel") == "old"
+ assert hooks.first_present("fake_sglang_new:gone", "fake_sglang_old:kernel") == "old"
+ with pytest.raises(ImportError, match="none of fake_sglang_gone:kernel"):
+ hooks.first_present("fake_sglang_gone:kernel")
+
+
+def test_the_verify_input_uses_the_installed_kv_indices_kernel():
+ from eagle_harness.sglang import verify_input
+
+ assert verify_input.create_flashinfer_kv_indices_triton is hooks.first_present(
+ "sglang.kernels.ops.attention.kv_indices:create_flashinfer_kv_indices_triton",
+ "sglang.kernels.ops.attention.utils:create_flashinfer_kv_indices_triton",
+ )
diff --git a/tests/test_sglang_plugin.py b/tests/test_sglang_plugin.py
index 455c34f..5976d6c 100644
--- a/tests/test_sglang_plugin.py
+++ b/tests/test_sglang_plugin.py
@@ -33,7 +33,7 @@ from sglang.srt.speculative.spec_registry import _REGISTRY # noqa: E402
import eagle_harness # noqa: E402
from eagle_harness.core.config import parse_harness_config # noqa: E402
-from eagle_harness.sglang import plugin # noqa: E402
+from eagle_harness.sglang import hooks, plugin # noqa: E402
from eagle_harness.sglang.algorithm import ALGORITHM_NAME, EagleHarnessSpecAlgo # noqa: E402
from eagle_harness.sglang.l2_warm import MlpL2WarmAhead # noqa: E402
from eagle_harness.sglang.verify_graphs import VerifyWidthGraphs, round_up_width, verify_widths # noqa: E402
@@ -366,7 +366,7 @@ def test_mamba2_tree_verify_follows_the_state_layout(registered):
from eagle_harness.sglang.gdn_tree_verify import GDNTreeVerify
from eagle_harness.sglang.mamba2_tree_verify import Mamba2TreeVerify
- if "kind" not in LinearAttnStateLayout.__dataclass_fields__:
+ if "kind" not in hooks.field_names(LinearAttnStateLayout):
pytest.skip("this sglang asks GDN backends only")
registered.__dict__["config"] = parse_harness_config(CONFIG)
state = dict(