Skip to content

Official Inference Code of EAGLE-4

chore(release): 0.1.3

Seyfal Sultanove110d1e91651
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a2c2438..ef12739 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,33 @@
# Changelog
+## [0.1.3]
+
+### Features
+
+* **pkg:** Support TokenSpeed through generic engine hooks, with EAGLE-4 policy and tree verification in the harness plugin. TokenSpeed serves EAGLE-4 in serve mode from calibrated cost tables. Static mode with the released EAGLE-4 draft is a known limit until 0.1.4.
+* **pkg:** Check sampled output distributions through the TokenSpeed API.
+
+### Performance
+
+* **sglang:** Serve the quick-start command with independent request admission and native decoding at high load.
+* **sglang:** Fill draft KV without prediction work for prompts admitted above the verify limit.
+
+### Bug fixes
+
+* **kernels:** Use 64-bit layer offsets when committing GDN records.
+* **core:** Stop `stop_check.py` with a usage error when the workload file has fewer conversations than concurrency times waves, thanks to @kevin9327.
+
+### Builds and installation
+
+* **pkg:** Build engine wheels and release images from approved inputs.
+* **pkg:** Explain server warm-up before throughput measurement.
+* **pkg:** Document the TokenSpeed 128K-token configuration measured on 0.1.2.
+* **pkg:** Document the TokenSpeed TVM helper's provenance.
+* **pkg:** Install CUDA redistributables with `cuda_redist.py` on Python 3.10, thanks to @kevin9327.
+* **pkg:** Keep added `License-File` headers in the metadata of wheels without a description, thanks to @kevin9327.
+* **pkg:** Write the wheel index root page for an index with no artifacts yet, thanks to @kevin9327.
+* **docs:** Fix grammar in the FAQ and known limits, thanks to @lunar-me.
+
## 0.1.2 (2026-10-23)
@@ -27,7 +55,7 @@
* **sglang:** serve with only the draft path by default, on SGLang's default overlap scheduler
* **sglang:** install the SGLang CUDA engine `0.5.23.dev252+eagle.5`
-* **tokenspeed:** install the TokenSpeed engine `0.1.1+eagle.5` (experimental)
+* **tokenspeed:** install the TokenSpeed engine build measured for 0.1.1 (since withdrawn; use the current install guide)
* **tokenspeed:** negotiate the plugin contract by capabilities
* **vllm:** answer vLLM's suspend_drafting and verify_budget hooks
* **core:** fp32 arbiter for greedy-parity divergences above the near-tie gap; a candidate that is the fp32 argmax passes
diff --git a/MANIFEST.in b/MANIFEST.in
index 4c9bae2..09742be 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -3,6 +3,7 @@ include LICENSE NOTICE TRADEMARKS.md README.md THIRD_PARTY_NOTICES.md
recursive-include LICENSES *.txt
recursive-include eagle_harness/core *.csv
recursive-include eagle_harness/kernels/csrc *.cu
+recursive-include eagle_harness/tokenspeed/tree_round/ops/csrc *.cu *.h
graft tests
prune eagle_harness/kernels/_native
global-exclude __pycache__ *.py[cod] *.so
diff --git a/README.md b/README.md
index 51c9d2c..c90af18 100644
--- a/README.md
+++ b/README.md
@@ -88,7 +88,7 @@ Or install with pip, in Python 3.12. Pip installs also need the [CUDA toolkit an
```bash
python3.12 -m venv .venv && source .venv/bin/activate
-pip install "eagle-harness[sglang]" "sglang==0.5.23.dev252+eagle.5" \
+pip install "eagle-harness[sglang]" "sglang==0.5.23.dev252+eagle.9" \
--extra-index-url https://eagle-hq.github.io/EAGLE-4/whl/cu130/ \
--extra-index-url https://download.pytorch.org/whl/cu130 \
--extra-index-url https://pypi.nvidia.com
@@ -107,6 +107,10 @@ curl http://localhost:30000/v1/chat/completions -H 'Content-Type: application/js
-d '{"model": "Qwen/Qwen3.8-27B", "messages": [{"role": "user", "content": "Explain how a hash table works."}], "max_tokens": 256}'
```
+The first requests after a start compile kernels and measure live costs, so they run slower. Send a few requests
+before you measure speed, and compare against the same command without the `--speculative-*` flags
+([benchmarking](docs/faq.md#how-do-i-benchmark-eagle-4)).
+
For vLLM, TokenSpeed and AMD MI355X, follow the [engine guides](#more).
## Measured speedup
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 78eb405..acf6ec1 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -14,6 +14,7 @@ points to the full license texts in [`LICENSES/`](LICENSES/).
| `eagle_harness/kernels/mamba2_tree.py` | `vllm/model_executor/layers/mamba/ops/mamba_ssm.py` (per-token selective state update) and `python/sglang/kernels/ops/mamba/triton_ops/mamba_ssm.py` (parent-state reload of the tree-mode update) | vLLM and sglang, which adapted it from mamba (state-spaces/mamba) | Apache-2.0 (vLLM, sglang, mamba) |
| `eagle_harness/sglang/models/llama_eagle4.py` | `python/sglang/srt/models/llama_eagle3.py` (decoder layer with the concatenated embedding and hidden-state input) | sglang, which adapted it from SafeAILab EAGLE `eagle/model/cnets.py` | Apache-2.0 (sglang, EAGLE) |
| `eagle_harness/sglang/tail_mask.py` | `include/flashinfer/attention/variants.cuh` (`DefaultAttention`, as the attention variant's template) | FlashInfer | Apache-2.0 |
+| `eagle_harness/tokenspeed/tree_round/ops/csrc/tvm_ffi_utils.h` | `tvm_ffi_utils.h` (tensor validation and CUDA stream interop) | FlashInfer | Apache-2.0 |
The engine adapters (`eagle_harness/sglang/`, `eagle_harness/vllm/`) also import, subclass and call sglang, vLLM and
FlashInfer classes at run time. That code is not copied into eagle-harness: it comes from the engine you install,
diff --git a/docs/architecture.md b/docs/architecture.md
index 19d0148..1eedcfa 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -106,15 +106,19 @@ eagle-harness supplies the tree policy and the draft model:
(`tests/test_tokenspeed_adapter.py`). `eagle_harness/tokenspeed/tree_lanes.py` turns the frontier choices into
TokenSpeed's 64-bit lane masks (each lane sees its ancestors' draft slots) and the verify window and parents.
-The EAGLE-4 draft layer has a sliding window. The pinned TokenSpeed release build supports sliding-window
-attention in tree lanes (every lane of a request sits at one position, so all lanes see the same committed keys).
+The EAGLE-4 draft layer has a sliding window. Serve mode runs its draft rounds in `eagle_harness/tokenspeed/tree_round`
+and serves this draft. The TokenSpeed 0.1.3 engine's own draft-tree lanes, which static mode uses, have no
+sliding-window path yet, so static mode stops at server start with that draft
+([known limits](known-limits.md#tokenspeed)).
Serve mode captures the target, sampling and draft extend together. The host launches the first draft-depth graph.
The GPU cost policy decides whether to continue and tail-launches later depths and finalization. Calibration parsing,
cost adjustments and depth thresholds come from the shared core cost model. `CostModel.tree_policy_costs()` exports
-immutable host cost records once at binding. The installed TokenSpeed engine packs these records and owns the
-device policy, draft-round graphs, tree kernels and tail-launch runtime; those implementations are not vendored in
-eagle-harness. Its GPU policy consumes the shared thresholds without a second host cost model.
+immutable host cost records once at binding. `eagle_harness/tokenspeed/tree_round` packs these records and owns the
+device policy, draft-round graphs, tree kernels and tail-launch runtime. Its GPU policy consumes the shared thresholds
+without a second host cost model. The package ships its CUDA sources and builds them with the harness compiler and
+cache helpers. TokenSpeed supplies generic plugin registration, round lifecycle, tree attention, scheduler headroom
+and recorded-proposal verification hooks.
For trees, the physical verify width stays fixed at `--speculative-num-draft-tokens`. A round can select fewer meaningful nodes
and pad the rest with unconnected roots. Draft lane slots `(steps - 1) * K` have their own KV reservation and must fit
diff --git a/docs/calibration.md b/docs/calibration.md
index 070882c..8f027e4 100644
--- a/docs/calibration.md
+++ b/docs/calibration.md
@@ -64,6 +64,12 @@ tables without a key (measured before keys existed) with a warning.
## Offline calibration
+TokenSpeed has a dedicated offline driver, `python -m eagle_harness.tokenspeed.measure_run`. It uses generic
+engine hooks to measure draft and target stages and writes the same shared cost-profile format that serve mode
+reads. It measures every batch size through `--max-bs`, rather than borrowing another engine's costs. See the
+[TokenSpeed calibration recipe](quickstart-tokenspeed.md#calibrate-costs) for matching TP, draft shape and state dtype.
+The `eagle-harness calibrate` frontend below selects SGLang or vLLM, not TokenSpeed.
+
Use `eagle-harness calibrate` to measure costs on the GPUs and engine you will serve with. It starts and stops
its own engine processes, retains raw measurements and prints a matching serving command. Stop other servers
on your allocated GPUs first.
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 7847845..0a35e8a 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -25,7 +25,7 @@ packages include the hooks or that every configuration in the range has been mea
| GPU and model pair | Configuration-specific qualification | [Support matrix](support-matrix.md) |
The release index carries patched engines with local version labels. Install those exact versions rather
-than assuming that the extras resolve to a compatible stock engine. TokenSpeed's scheduler and kernel
+than assuming that the extras resolve to a compatible stock engine. TokenSpeed's scheduler, kernel and control-plane
packages must come from the same release source as its runtime package.
The pinned vLLM build includes KV cache group sizing, a decode GEMM used with
diff --git a/docs/configuration.md b/docs/configuration.md
index 2472f51..e5525cd 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -22,6 +22,7 @@ For legacy environment variables and CLI flags, see [Migration](migration.md).
| `cost_model` | object | see below | Cost model constants. |
| `draft_model` | object | see below | EAGLE-4 draft model options. |
| `l2_warm` | object | see below | L2 prefetches of target weights inside the sglang verify graphs. |
+| `max_verify_batch_size` | integer | none | SGLang: the largest batch that speculates; larger batches decode natively, and a hybrid target keeps per-step verify states for that many requests only. Without `--max-running-requests`, the default is 32 for a tree and 48 for a chain, and the engine admits as many requests as its memory allows (as without speculation), up to the tree or chain batch limit. None with `--max-running-requests`: every running batch may speculate. |
## `cost_model`
@@ -102,7 +103,9 @@ whole target off FlashInfer. Keep the target backend unchanged for a matched spe
TokenSpeed 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.
+server refuses to start. `"mode": "static"` uses every configured draft step and needs no cost data. With the
+released EAGLE-4 draft, whose attention layer uses a sliding window, the TokenSpeed 0.1.3 engine stops static mode
+at server start ([known limits](known-limits.md#tokenspeed)), so serve with `"mode": "serve"`.
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.
@@ -110,7 +113,9 @@ For calibrated tree serving, provide `data_path` containing the calibration `cos
The [TokenSpeed quickstart](quickstart-tokenspeed.md) distinguishes the single-client cap of 4 from the
concurrent cap of 32. Neither is a general performance recommendation.
The calibration must match the target, draft, hardware, tensor-parallel setup and recurrent-state dtype.
-`calibrate` and live costs are not supported by this adapter. Chains use top-k 1 and `chain_intensity`.
+Use the [TokenSpeed calibration driver](quickstart-tokenspeed.md#calibrate-costs) to measure every batch size
+up to the server's request limit. Live cost updates during serving are not supported.
+Chains use top-k 1 and `chain_intensity`.
An explicit `chain_width_table` contains increasing `[minimum_batch_size, verify_width]` pairs in `serve` mode.
A complete schedule starting at batch size 1 does not need cost files. This describes the configuration interface,
not a measured high-concurrency speed claim. Sampled-tree distribution quality is unqualified.
diff --git a/docs/faq.md b/docs/faq.md
index 5b3514d..93316ce 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -20,6 +20,24 @@ Choose an engine with measured coverage for your model pair and request features
[support matrix](support-matrix.md). SGLang picks the verify width per round. vLLM fixes that width per batch size,
so only the draft depth adapts per round.
+## How do I benchmark EAGLE-4?
+
+- 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`.
+- 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.
+- Report decoding and prefill separately. Speculative decoding speeds up decoding, not prefill. With long
+ prompts and short replies, as in agentic workloads, time to first token is a large share of each request, so
+ end-to-end speedups are lower than decoding speedups for every speculative method. Report decoding throughput
+ (first to last output token) and time to first token.
+- Measure at the temperature you serve. At temperature 1, SGLang verifies a sampled draft tree. Other
+ temperatures use a greedy draft verified by the target's sampler
+ ([known limits](known-limits.md#performance-and-correctness-in-progress)).
+
## Do I need cost tables?
When no `data_path` is supplied, SGLang selects a matching packaged MI355X profile if available, otherwise
diff --git a/docs/install.md b/docs/install.md
index e59674b..f71ea3d 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -24,7 +24,7 @@ containers, use a [published image](#docker-images) instead.
```bash
python3.12 -m venv .venv && source .venv/bin/activate
-pip install "eagle-harness[sglang]" "sglang==0.5.23.dev252+eagle.5" \
+pip install "eagle-harness[sglang]" "sglang==0.5.23.dev252+eagle.9" \
--extra-index-url https://eagle-hq.github.io/EAGLE-4/whl/cu130/ \
--extra-index-url https://download.pytorch.org/whl/cu130 \
--extra-index-url https://pypi.nvidia.com
@@ -47,13 +47,16 @@ Then follow the [vLLM guide](quickstart-vllm.md).
```bash
python3.12 -m venv .venv && source .venv/bin/activate
-pip install "eagle-harness[tokenspeed]" "tokenspeed==0.1.1+eagle.5" \
- "tokenspeed-scheduler==0.1.40+eagle.4" "tokenspeed-kernel==0.1.4+eagle.5" \
+pip install "eagle-harness[tokenspeed]" "tokenspeed==0.1.1+eagle.8" \
+ "tokenspeed-scheduler==0.1.42+eagle.8" "tokenspeed-kernel==0.1.4+eagle.8" \
+ "tokenspeed-engine==0.1.0+eagle.8" \
--extra-index-url https://eagle-hq.github.io/EAGLE-4/whl/cu130/ \
--extra-index-url https://download.pytorch.org/whl/cu130
```
-TokenSpeed runs on NVIDIA GPUs only. Then follow the [TokenSpeed guide](quickstart-tokenspeed.md).
+TokenSpeed runs on NVIDIA GPUs only. Then follow the [TokenSpeed guide](quickstart-tokenspeed.md), which calibrates
+cost tables and serves in serve mode. Static mode does not start with the released EAGLE-4 draft in this release
+([known limits](known-limits.md#tokenspeed)).
## What the indexes and pins are for
@@ -62,11 +65,11 @@ TokenSpeed runs on NVIDIA GPUs only. Then follow the [TokenSpeed guide](quicksta
| `https://eagle-hq.github.io/EAGLE-4/whl/cu130/` | The patched SGLang, vLLM and TokenSpeed wheels. They carry a `+eagle.N` local version, so pip picks them only when the command pins that exact version. |
| `https://download.pytorch.org/whl/cu130` | PyTorch built for CUDA 13.0, which the engine wheels need. |
| `https://pypi.nvidia.com` | The `cuda-tile==1.6.0rc5` wheel that the SGLang engine pins. Without it pip builds that package from source. |
-| `tokenspeed-scheduler`, `tokenspeed-kernel` | TokenSpeed's native packages, built from the same source as the engine. The stock wheels do not work with it. |
+| `tokenspeed-scheduler`, `tokenspeed-kernel`, `tokenspeed-engine` | TokenSpeed's native packages and control plane, built from the same source as the engine. Install the matching versions together. |
The engine wheels are assets of the [v0.1.0 GitHub release](https://github.com/eagle-hq/EAGLE-4/releases/tag/v0.1.0),
and the index pages link to them with SHA-256 hashes. Their sources are [eagle-hq/sglang](https://github.com/eagle-hq/sglang),
-[eagle-hq/vllm](https://github.com/eagle-hq/vllm) and [eagle-hq/tokenspeed](https://github.com/eagle-hq/tokenspeed).
+[eagle-hq/vllm](https://github.com/eagle-hq/vllm) and [eagle-hq/tokenspeed, `eagle/v0.1.3`](https://github.com/eagle-hq/tokenspeed/tree/eagle/v0.1.3).
`eagle-harness` itself is published only on PyPI.
[docs/release.env](release.env) holds the same pins and URLs for scripts and image builds.
[docker/sglang/requirements.lock](../docker/sglang/requirements.lock) pins the SGLang CUDA runtime dependencies by
@@ -81,7 +84,7 @@ command for each one.
| --- | --- |
| SGLang CUDA | `ghcr.io/eagle-hq/eagle-4-sglang:0.1.2` |
| vLLM CUDA | `ghcr.io/eagle-hq/eagle-4-vllm:0.1.2` |
-| TokenSpeed CUDA | `ghcr.io/eagle-hq/eagle-4-tokenspeed:0.1.2` |
+| TokenSpeed CUDA | `ghcr.io/eagle-hq/eagle-4-tokenspeed:0.1.3` |
| SGLang ROCm | not published, [build it](#build-the-rocm-image) |
To run a newer `eagle-harness` in an image, run `pip install -U eagle-harness` inside the container.
diff --git a/docs/known-limits.md b/docs/known-limits.md
index 61ac1e0..0d9c759 100644
--- a/docs/known-limits.md
+++ b/docs/known-limits.md
@@ -28,18 +28,13 @@ kernel is a startup check.
On SGLang with four GPUs, the [high-load recipe](quickstart-sglang.md#high-load) keeps pace with plain decoding up
to 512 concurrent requests. These limits apply around it:
-- The SGLang command of the README quick start is slower than plain decoding above about 32 to 64 concurrent
- requests. On one B300 it measured 0.73× the same engine without speculation at concurrency 64 and 0.59× at 256.
- With `--tp-size 4` it measured 0.80× at 64, 0.48× at 128, 0.37× at 256 and 0.32× at 512 (2 starts each). Three
- settings cause it. The radix cache, on by default, makes this hybrid model track prefix-cache state that a batch
- switching to plain decoding cannot carry yet, so the server speculates at every load. The default tree caps a
- four-GPU server at 32 running requests, while plain decoding admits several hundred. On one GPU, the engine
- reserves verify state for every admitted request, so a speculative server admits about a quarter of the
- requests plain decoding does. For high load on four GPUs, use the high-load recipe. A fix for the default
- command is planned.
-- High load on one GPU is not supported yet. On one GPU, a speculative server started with
- `--disable-radix-cache` stops during draft graph capture, so keep the radix cache on there. The high-load recipe
- is for four GPUs, and the server log's advice to add `--disable-radix-cache` applies to four GPUs only.
+- The SGLang command of the README quick start decodes without speculation at high load. With its default cache
+ settings it measured 1.00× the same engine without speculation at 64, 128 and 256 concurrent requests and 0.99×
+ at 512 on one B300, and from 0.99× to 1.03× at 64 to 512 on four (4 starts each). On four GPUs at 8 concurrent
+ requests its throughput is 0.97× that of 0.1.2 ([0.1.3 release notes](release-notes/0.1.3.md#limits)).
+- On one GPU, a speculative server started with `--disable-radix-cache` stops during draft graph capture, so keep
+ the radix cache on there. The high-load recipe is for four GPUs, and the server log's advice to add
+ `--disable-radix-cache` applies to four GPUs only.
- The first start of the high-load recipe on a machine compiles kernels and measures its live costs during its
first requests. It measured 0.95× at 64 and 0.97× at 128 concurrent requests, and restarts with warm caches
1.01× and 1.00× (3 starts each).
@@ -64,6 +59,12 @@ to 512 concurrent requests. These limits apply around it:
## Performance and correctness in progress
+- SGLang greedy correctness at 64 or more concurrent requests: 7 of 12,096 checked outputs in the 0.1.3 release
+ check fall outside the fp32 tolerance and are not reproduced by plain decoding at the same prefix. They are on the
+ one-GPU README command at 128 concurrent requests (one prompt in each of four starts), the four-GPU measured
+ recipe at 64 (one prompt in each of two starts) and the four-GPU high-load recipe at 512 (one prompt in one
+ start). Version 0.1.4 compares against plain decoding at the same batch size
+ ([0.1.3 release notes](release-notes/0.1.3.md#limits)).
- SGLang TP4 single-request and 32K-context optimization is in progress, as are TP8 concurrency-8 prefill
overhead and intermittent stalls. Repeated passes in one process are not independent server starts.
- SGLang native-OFF, including OFF forced by a cost profile, uses the engine's per-variant forward-mode
@@ -108,12 +109,18 @@ to 512 concurrent requests. These limits apply around it:
## TokenSpeed
-TokenSpeed serves EAGLE-4 with static and calibrated trees, chains and sampled trees on NVIDIA GPUs. Install the
+TokenSpeed serves EAGLE-4 in serve mode with calibrated trees, chains and sampled trees on NVIDIA GPUs. Install the
engine, its native packages and `eagle-harness` together with the [install command](install.md#tokenspeed-cuda),
-because the adapter needs the matching engine hooks. The 0.1.2 measurements cover serve mode at TP1 and TP4,
-temperature 0 and 1, 32K-token contexts and four-GPU chains
+because the adapter needs the matching engine hooks. On four B300 GPUs, the 0.1.3 build passed TP4 calibration,
+greedy serving from that profile (twenty prompts: 3 identical, 17 first divergences within the fp32 tolerance) and
+sampled tree serving at temperature 1. The 0.1.2 measurements cover serve mode at TP1, TP4 and TP8, temperature 0
+and 1, 32K- and 128K-token contexts and four-GPU chains on the 0.1.2 engine build
([support matrix](support-matrix.md#012-speed-by-engine-and-concurrency)).
+- Static mode (`"mode": "static"`) stops at server start with the released EAGLE-4 draft, whose attention layer
+ uses a 4096-token sliding window. The TokenSpeed 0.1.3 engine raises `draft trees have no sliding-window or
+ attention-sink path yet` when it builds the draft tree. Serve mode runs the draft tree in `eagle-harness` and
+ is not affected. Static-mode support for sliding-window drafts is planned for 0.1.4.
- TokenSpeed runs on CUDA only. On AMD GPUs, serve with SGLang ROCm ([AMD guide](quickstart-amd.md)).
- On one GPU, start the server with `--disable-kvstore`. By default TokenSpeed adds a host KV cache tier twice the
size of the GPU's KV cache, and a one-GPU server cannot pin that much host memory. The guide's commands pass the
@@ -132,15 +139,15 @@ temperature 0 and 1, 32K-token contexts and four-GPU chains
is not a native no-speculation round.
- Live cost measurement: serve mode reads cost tables measured for TokenSpeed.
- Serve mode needs cost tables measured for TokenSpeed. Tree and chain cost data should match the served shape, TP
- size, target, draft and recurrent-state dtype. Only TP4 tables exist; the TP1 and TP8 measurements reuse them.
+ size, target, draft and recurrent-state dtype. EAGLE-4 0.1.3 ships no TokenSpeed tables: calibrate once on your
+ setup ([TokenSpeed guide](quickstart-tokenspeed.md#calibrate-costs)). The 0.1.3 build was checked at TP4. TP1,
+ TP8 and chains were measured on 0.1.2.
- Retraction is not qualified. TokenSpeed reserves pages when it admits a request and queues the rest, so the
measured servers never retract. With retractions forced by a test-only setting, one prompt in three chain starts
fails the fp32 rule ([support matrix](support-matrix.md#012-correctness-and-request-features)).
- EAGLE-3 drafts are not checked on TokenSpeed. TP4 single-request optimization is in progress.
-- Static mode is a setup check, because its CUDA install smoke generates text with one first divergence above the
- fp32 gate. The serve-mode install smoke passes its greedy prompts with the CUDA 13.2 JIT. On Ubuntu 26.04 / glibc
- 2.43, set `CUDA_HOME` to CUDA 13.2 ([troubleshooting](troubleshooting.md#install-problems)). These checks cover
- the toolkits named here.
+- On Ubuntu 26.04 / glibc 2.43, set `CUDA_HOME` to CUDA 13.2 before the first start, which compiles the
+ tree-round CUDA sources ([troubleshooting](troubleshooting.md#install-problems)).
## Calibration
@@ -161,15 +168,13 @@ The [install guide](install.md) describes the release path: `eagle-harness` pack
patched engine wheels on the GitHub Pages indexes, and images on GHCR. Model and draft weights come from
Hugging Face under their owners' licenses.
-- The published SGLang and vLLM images passed serving and correctness checks, and the published TokenSpeed image
- passed a GPU check in serve mode ([support matrix](support-matrix.md#011-installation-checks)). They carry
- `eagle-harness` 0.1.1 and the 0.1.1 engines. Use the image commands in the engine guides with them.
+- Use the [install guide](install.md#docker-images) for image versions. TokenSpeed's `:0.1.3` image uses the
+ hooks-only engine and harness plugin; earlier TokenSpeed image checks are historical, not qualification of this build.
- The files under `docker/` show how the release images are built. The checked CUDA images carry a prebuilt
`eagle-harness` wheel, so the published images are the checked path. The TokenSpeed Dockerfile takes an
explicit compatible `BASE_IMAGE`.
- On AMD, install with pip: the ROCm closure is clean-installed from the public indexes and inference-tested on
an MI355X. The ROCm Dockerfile is being container-qualified, and no ROCm image is published yet.
-- TokenSpeed serve mode uses cost tables measured for TokenSpeed on the served setup. EAGLE-4 does not ship them
- or a command that measures them yet, so the [TokenSpeed guide](quickstart-tokenspeed.md) starts in static
- mode as a setup check.
+- TokenSpeed serve mode uses cost tables measured for TokenSpeed on the served setup. EAGLE-4 does not ship them,
+ so the [TokenSpeed guide](quickstart-tokenspeed.md) calibrates them before the first server start.
- Use the pinned artifacts: stock engines and unpinned packages do not carry the EAGLE-4 hooks.
diff --git a/docs/quickstart-tokenspeed.md b/docs/quickstart-tokenspeed.md
index 67e498f..aee0aab 100644
--- a/docs/quickstart-tokenspeed.md
+++ b/docs/quickstart-tokenspeed.md
@@ -1,89 +1,106 @@
---
type: tutorial
owner: eagle-harness
-last_verified: 2026-10-23
+last_verified: 2026-10-26
---
# TokenSpeed guide
-Serve Qwen3.8-27B and its EAGLE-4 draft with TokenSpeed on NVIDIA GPUs. Its measured cost-model mode needs cost
-tables that EAGLE-4 does not ship yet, so the first server below uses a static tree to check that generation works.
+Serve Qwen3.8-27B and its EAGLE-4 draft with TokenSpeed on NVIDIA GPUs. TokenSpeed serves EAGLE-4 in serve mode,
+where the cost model sizes every round from cost tables measured on your serving setup. EAGLE-4 0.1.3 ships no
+TokenSpeed cost tables, so calibrate once with the driver below, then start the server with that profile.
-## Start a server
-
-Install the engine with the [TokenSpeed install command](install.md#tokenspeed-cuda), then start a
-server with a static tree:
-
-```bash
-tokenspeed serve Qwen/Qwen3.8-27B --disable-kvstore \
- --attention-backend trtllm --max-model-len 65536 --sampling-backend greedy \
- --speculative-algorithm EAGLE_HARNESS \
- --speculative-draft-model-path EAGLE-Corp/Qwen3.8-27B-EAGLE4 \
- --speculative-num-steps 5 --speculative-eagle-topk 4 --speculative-num-draft-tokens 16 \
- --speculative-algorithm-config '{"mode": "static"}'
-```
-
-The command serves on one GPU. `--disable-kvstore` turns off TokenSpeed's host-memory KV cache tier, which by
-default pins twice the GPU's KV cache in host memory; the measured recipe turns it off too. Add
-`--tensor-parallel-size 4` to serve on four, as the measured recipe below does.
+Install the engine with the [TokenSpeed install command](install.md#tokenspeed-cuda) first. Static mode
+(`"mode": "static"`) stops at server start with the released EAGLE-4 draft in this release
+([known limits](known-limits.md#tokenspeed)).
-Static mode drafts the full tree every round, without a cost model. Its twenty-prompt greedy check has one
-first divergence above the fp32 gate, so it checks setup rather than correctness
-([known limits](known-limits.md#tokenspeed)). `--sampling-backend greedy` is required, because
-draft trees are verified by the greedy and triton sampling backends.
+## Calibrate costs
-## Send a request
+Stop other servers on your allocated GPUs, choose a fresh output directory, and measure the same draft shape and
+TP size you will serve:
```bash
-curl http://localhost:8000/v1/chat/completions -H 'Content-Type: application/json' \
- -d '{"model": "Qwen/Qwen3.8-27B", "messages": [{"role": "user", "content": "Explain how a hash table works."}], "max_tokens": 256}'
+export COST_ROOT=$PWD/tokenspeed-tp4-costs
+python -m eagle_harness.tokenspeed.measure_run \
+ --model Qwen/Qwen3.8-27B --draft-model EAGLE-Corp/Qwen3.8-27B-EAGLE4 \
+ --run-dir "$COST_ROOT" --tp-size 4 --compute-intensity high_intensity \
+ --topk 4 --num-steps 12 --num-draft-tokens 16 --max-bs 32 \
+ --mamba-ssm-dtype float32
```
-The response holds the generated message. The first start compiles tree-round CUDA sources, which needs `nvcc`.
-On Ubuntu 26.04 / glibc 2.43, set `CUDA_HOME=/usr/local/cuda-13.2` first ([troubleshooting](troubleshooting.md#install-problems)).
+The driver starts its own greedy engine in `calibrate` mode, measures draft and target stages with CUDA events,
+then measures tree-cascade attention over the context grid. It uses the shared calibration records and robust fits
+to write `test/bs_<N>/` raw timings and `cost/bs_<N>/model_{slm,llm}/` profiles for every batch size from 1 through
+`--max-bs`. Unstable fits are retried up to three times and a failed batch stops the command. Keep partial output
+for diagnosis, but use only a completed profile for serving.
-## The measured recipe
+Calibration requests commit fixed tokens to control context growth. They are measurement traffic, not useful
+generation or a correctness test. Costs must match GPU, model pair, engine build, TP, draft shape, attention backend
+(`trtllm`), weight dtype (`bfloat16`) and Mamba state dtype. The driver records its settings in
+`config/tokenspeed.json`. Recalibrate when any of these change. The default context grid ends at 8192 tokens.
+Use `--context-stop` and `--context-step` for a longer grid. This is offline calibration, not live cost adaptation.
+The first engine start compiles kernels and tunes GEMMs, which took about 20 minutes on an empty cache.
+
+## Start a server
-The TokenSpeed rows of the [support matrix](support-matrix.md#011-speed-by-engine-and-concurrency) use serve mode, where the
-cost model sizes every round from cost tables measured for TokenSpeed on B300 at TP4. Set `COST_ROOT` to a
-directory whose `cost/` folder holds such tables. vLLM and ROCm tables are not substitutes.
+Point `data_path` at the completed calibration and start serve mode on the same four GPUs:
```bash
-export COST_ROOT=/path/to/tokenspeed-tp4-costs
-tokenspeed serve Qwen/Qwen3.8-27B --tensor-parallel-size 4 \
+tokenspeed serve Qwen/Qwen3.8-27B --tensor-parallel-size 4 --dtype bfloat16 \
--attention-backend trtllm --max-model-len 65536 --max-num-seqs 32 \
--disable-kvstore --seed 721 --gpu-memory-utilization 0.6 --disable-prefix-caching \
- --reasoning-parser qwen3 --sampling-backend greedy \
+ --reasoning-parser qwen3 --sampling-backend greedy --mamba-ssm-dtype float32 \
--speculative-algorithm EAGLE_HARNESS \
--speculative-draft-model-path EAGLE-Corp/Qwen3.8-27B-EAGLE4 \
--speculative-num-steps 12 --speculative-eagle-topk 4 --speculative-num-draft-tokens 16 \
--speculative-algorithm-config "{\"mode\": \"serve\", \"data_path\": \"$COST_ROOT\"}"
```
+`--dtype bfloat16` matches the calibration engine, so the server reuses its GEMM tuning instead of tuning again.
+`--disable-kvstore` turns off TokenSpeed's host-memory KV cache tier, which by default pins twice the GPU's KV
+cache in host memory. `--sampling-backend greedy` is required, because draft trees are verified by the greedy and
+triton sampling backends. vLLM and ROCm cost tables are not substitutes.
+
The single-client recipe uses `--max-num-seqs 4` and the concurrent recipe `--max-num-seqs 32`. Neither setting
-promises a speedup for your workload. The serve-mode check passed twenty greedy prompts with 4 exact and 16
-fp32-tolerance results. These are first-divergence checks, not bitwise output equality or sampled-distribution
-qualification.
+promises a speedup for your workload. On four B300 GPUs this command, with a fresh TP4 calibration, served twenty
+greedy prompts with 3 outputs identical to TokenSpeed without speculation and 17 first divergences within the fp32
+tolerance, the same in two independent starts. These are first-divergence checks, not bitwise output equality or
+sampled-distribution qualification.
-The same command serves one GPU with `--tensor-parallel-size 1` (it reuses the TP4 tables; no TP1 tables exist
-yet) and 32K-token prompts within `--max-model-len 65536`. The
-[support matrix](support-matrix.md#012-speed-by-engine-and-concurrency) has one row per setup.
+For one GPU, calibrate with `--tp-size 1` and serve with `--tensor-parallel-size 1`, using that new profile rather
+than TP4 costs. The server also supports 32K-token prompts within `--max-model-len 65536`. The
+[support matrix](support-matrix.md#012-speed-by-engine-and-concurrency) has one row per setup measured on 0.1.2.
+
+## Send a request
+
+```bash
+curl http://localhost:8000/v1/chat/completions -H 'Content-Type: application/json' \
+ -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. The first start compiles tree-round CUDA sources, which needs `nvcc`.
+Send a few requests before you measure speed ([benchmarking](faq.md#how-do-i-benchmark-eagle-4)).
+On Ubuntu 26.04 / glibc 2.43, set `CUDA_HOME=/usr/local/cuda-13.2` first ([troubleshooting](troubleshooting.md#install-problems)).
## Sampled requests
For temperature above 0, sample with FlashInfer, one random stream per batch, and speculative sampling. A draft
-tree runs at most 32 requests at a time:
+tree runs at most 32 requests at a time. The harness supplies its rejection sampler through TokenSpeed's
+`sampling.tree_sampler` hook. The sampler and CUDA sources ship under the Eagle license in `eagle-harness`,
+not in the engine. Native EAGLE-3 and MTP keep TokenSpeed's greedy and position-keyed Triton tree verification.
+Installing the harness does not bind a sampler for native drafters.
+
+Start sampled serving with:
```bash
-tokenspeed serve Qwen/Qwen3.8-27B --tensor-parallel-size 4 \
+tokenspeed serve Qwen/Qwen3.8-27B --tensor-parallel-size 4 --dtype bfloat16 \
--attention-backend trtllm --max-model-len 65536 --max-num-seqs 32 \
--disable-kvstore --seed 721 --gpu-memory-utilization 0.6 --disable-prefix-caching \
- --reasoning-parser qwen3 --sampling-backend flashinfer --sampling-stream batch \
+ --reasoning-parser qwen3 --sampling-backend flashinfer --sampling-stream batch --mamba-ssm-dtype float32 \
--speculative-algorithm EAGLE_HARNESS \
--speculative-draft-model-path EAGLE-Corp/Qwen3.8-27B-EAGLE4 \
--speculative-num-steps 12 --speculative-eagle-topk 4 --speculative-num-draft-tokens 16 \
- --speculative-algorithm-config "{\"mode\": \"serve\", \"data_path\": \"$COST_ROOT\"}" \
- --enable-speculative-sampling
+ --speculative-algorithm-config "{\"mode\": \"serve\", \"data_path\": \"$COST_ROOT\", \"sampled_proposals\": true}"
```
To run more than 32 requests at a time, serve chains, which need no cost tables:
@@ -96,12 +113,11 @@ tokenspeed serve Qwen/Qwen3.8-27B --tensor-parallel-size 4 \
--speculative-algorithm EAGLE_HARNESS \
--speculative-draft-model-path EAGLE-Corp/Qwen3.8-27B-EAGLE4 \
--speculative-num-steps 7 --speculative-eagle-topk 1 --speculative-num-draft-tokens 8 \
- --speculative-algorithm-config '{"mode": "serve", "intensity": "chain_intensity", "chain_width_table": [[1, 8], [32, 4]]}' \
- --enable-speculative-sampling
+ --speculative-algorithm-config '{"mode": "serve", "intensity": "chain_intensity", "chain_width_table": [[1, 8], [32, 4]], "sampled_proposals": true}'
```
-At 64 concurrent requests the chain server measured 1.12× its no-spec
-control at temperature 1, the tree server 0.87×. `tools/sampling_check.py run --api tokenspeed` compares a sampled
+On 0.1.2, at 64 concurrent requests, the chain server measured 1.12× its no-spec
+control at temperature 1 and the tree server 0.87×. `tools/sampling_check.py run --api tokenspeed` compares a sampled
server with a no-spec server; top-k/top-p and min-p follow TokenSpeed's own filters
([known limits](known-limits.md#tokenspeed)).
diff --git a/docs/release-notes/0.1.1.md b/docs/release-notes/0.1.1.md
index 836a8f6..a0ab8b3 100644
--- a/docs/release-notes/0.1.1.md
+++ b/docs/release-notes/0.1.1.md
@@ -20,11 +20,11 @@ environment, run your engine's install command with the pins below, then `eagle-
| --- | --- |
| SGLang CUDA | `eagle-harness[sglang]==0.1.1`, `sglang==0.5.23.dev252+eagle.5` |
| vLLM | `eagle-harness[vllm]==0.1.1`, `vllm==0.32.0rc1.dev283+eagle.4` (unchanged) |
-| TokenSpeed | `eagle-harness[tokenspeed]==0.1.1`, `tokenspeed==0.1.1+eagle.5`, `tokenspeed-kernel==0.1.4+eagle.5`, `tokenspeed-scheduler==0.1.40+eagle.4` |
+| TokenSpeed | This engine build was withdrawn. Use the current [TokenSpeed install command](../install.md#tokenspeed-cuda), not the historical build measured below. |
-The images `ghcr.io/eagle-hq/eagle-4-sglang:0.1.1`, `ghcr.io/eagle-hq/eagle-4-vllm:0.1.1` and
-`ghcr.io/eagle-hq/eagle-4-tokenspeed:0.1.1` carry these engines with `eagle-harness` 0.1.1. The
-[install guide](../install.md#docker-images) lists them.
+The SGLang and vLLM `:0.1.1` images carried these engines with `eagle-harness` 0.1.1.
+The TokenSpeed image from this release was withdrawn. The [install guide](../install.md#docker-images)
+lists the current images.
**Breaking:** the configuration is streamlined. A config that still sets `"mode": "eval"`, `ragged`
(`enabled`, `force_uniform`), `cost_model.ragged_draft_relax`, `cost_model.ragged_verify_threshold` or
@@ -61,7 +61,7 @@ removed option and environment variable. No shipped configuration uses them.
matches the GPU, TP size, model pair, engine and dtype being served.
**TokenSpeed**
-- The engine build `tokenspeed==0.1.1+eagle.5` with `tokenspeed-kernel==0.1.4+eagle.5`. Its TP4 serve-mode
+- The now-withdrawn TokenSpeed engine build measured for 0.1.1. Its historical TP4 serve-mode
speedups are in the [support matrix](../support-matrix.md#011-speed-by-engine-and-concurrency).
- Serve mode is the default, as on the other engines. A launch needs a `data_path` or a complete schedule;
`{"mode": "static"}` selects static mode.
diff --git a/docs/release-notes/0.1.2.md b/docs/release-notes/0.1.2.md
index 15e58d7..95946f7 100644
--- a/docs/release-notes/0.1.2.md
+++ b/docs/release-notes/0.1.2.md
@@ -21,10 +21,11 @@ environment, run your engine's install command with the pins below, then `eagle-
| --- | --- |
| SGLang CUDA | `eagle-harness[sglang]==0.1.2`, `sglang==0.5.23.dev252+eagle.5` (unchanged) |
| vLLM | `eagle-harness[vllm]==0.1.2`, `vllm==0.32.0rc1.dev283+eagle.4` (unchanged) |
-| TokenSpeed | `eagle-harness[tokenspeed]==0.1.2`, `tokenspeed==0.1.1+eagle.5`, `tokenspeed-kernel==0.1.4+eagle.5`, `tokenspeed-scheduler==0.1.40+eagle.4` (unchanged) |
+| TokenSpeed | This engine build was withdrawn. Use the current [TokenSpeed install command](../install.md#tokenspeed-cuda), not the historical build measured below. |
-The `:0.1.2` images carry `eagle-harness` 0.1.2 on the same engines. The [install guide](../install.md#docker-images)
-lists them. Nothing in the configuration changes: every 0.1.1 configuration loads as before.
+The SGLang and vLLM `:0.1.2` images carry `eagle-harness` 0.1.2 on the same engines. The TokenSpeed image from
+this release was withdrawn. The [install guide](../install.md#docker-images) lists the current images.
+Nothing in the 0.1.2 configuration changed: every 0.1.1 configuration loaded as before.
## What changed
diff --git a/docs/release-notes/0.1.3.md b/docs/release-notes/0.1.3.md
new file mode 100644
index 0000000..6e2f3e6
--- /dev/null
+++ b/docs/release-notes/0.1.3.md
@@ -0,0 +1,65 @@
+# EAGLE-4 0.1.3
+
+EAGLE-4 combines a draft model with `eagle-harness` inside your inference engine to adapt speculative decoding to your hardware, batch and workload. Version 0.1.3 brings native decoding at high load to the SGLang README command, including the one-GPU setup, and fills draft KV without prediction work for prompts admitted above the verify limit. It also builds engine wheels and release images from approved inputs and explains how to warm up a server before measuring it.
+
+This release ships SGLang CUDA `0.5.23.dev252+eagle.9`, keeps vLLM `0.32.0rc1.dev283+eagle.4` unchanged, and adds TokenSpeed `0.1.1+eagle.8`, built from [eagle-hq/tokenspeed `eagle/v0.1.3`](https://github.com/eagle-hq/tokenspeed/tree/eagle/v0.1.3). The TokenSpeed engine exposes generic engine hooks, and EAGLE-4 policy and tree verification live in the harness plugin. TokenSpeed serves EAGLE-4 in serve mode from cost tables you calibrate once on your setup. On four B300 GPUs this build passed calibration, greedy serving from the calibrated profile (twenty prompts: 3 identical to TokenSpeed without speculation, 17 first divergences within the fp32 tolerance, the same in two starts) and sampled serving at temperature 1. TokenSpeed's 0.1.2 speed measurements remain historical results, not measurements of this build.
+
+## Install
+
+You don't need to download anything from the release page. In a Python 3.12 environment, install the SGLang packages together:
+
+```bash
+pip install "eagle-harness[sglang]==0.1.3" "sglang==0.5.23.dev252+eagle.9" \
+ --extra-index-url https://eagle-hq.github.io/EAGLE-4/whl/cu130/ \
+ --extra-index-url https://download.pytorch.org/whl/cu130 \
+ --extra-index-url https://pypi.nvidia.com
+```
+
+Follow the [SGLang guide](../quickstart-sglang.md), [vLLM guide](../quickstart-vllm.md) or [TokenSpeed guide](../quickstart-tokenspeed.md) to serve an EAGLE-4 draft. Install TokenSpeed with its matching scheduler, kernel and control-plane wheels using the [install guide](../install.md#tokenspeed-cuda). The TokenSpeed image is `:0.1.3`; SGLang and vLLM keep their documented `:0.1.2` images until their `:0.1.3` image checks finish.
+
+## Measured speed
+
+These measurements use Qwen3.8-27B with the EAGLE-4 draft on NVIDIA B300 GPUs and greedy decoding. Each cell is EAGLE-4 output throughput divided by the same engine's throughput without speculation, averaged over four starts per configuration. Client concurrency ranges from 1 to 512 for the README and high-load recipes, and from 1 to 64 for the measured recipes. Controls use the same recipe, tensor-parallel size and running-request cap. These throughput results do not imply a passing correctness check, as described below.
+
+| Engine and command | GPUs | 1 request | 8 | 64 | 128 | 256 | 512 |
+| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
+| SGLang README | 1 | 2.93× | 1.99× | 1.00× | 1.00× | 1.00× | 0.99× |
+| SGLang README | 4 | 2.34× | 1.64× | 0.99× | 1.00× | 1.02× | 1.03× |
+| SGLang measured recipe | 4 | 3.37× | 2.06× | 1.27× | Not measured | Not measured | Not measured |
+| SGLang high-load recipe | 4 | 2.90× | 1.81× | 1.00× | 0.98× | 1.01× | 0.99× |
+| vLLM measured recipe | 4 | 2.91× | 1.74× | 1.00× | Not measured | Not measured | Not measured |
+
+The corresponding EAGLE-4 throughput is in output tokens per second:
+
+| Engine and command | GPUs | 1 request | 8 | 64 | 128 | 256 | 512 |
+| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
+| SGLang README | 1 | 309.5 | 1,356.6 | 3,336.8 | 3,975.7 | 3,764.4 | 3,714.5 |
+| SGLang README | 4 | 577.7 | 2,549.3 | 8,083.9 | 12,614.1 | 17,079.3 | 18,687.9 |
+| SGLang measured recipe | 4 | 736.5 | 2,959.6 | 5,699.3 | Not measured | Not measured | Not measured |
+| SGLang high-load recipe | 4 | 729.7 | 2,972.0 | 8,321.0 | 12,134.7 | 15,447.2 | 17,216.5 |
+| vLLM measured recipe | 4 | 696.5 | 2,632.1 | 7,135.1 | Not measured | Not measured | Not measured |
+
+The [SGLang high-load recipe](../quickstart-sglang.md#high-load) and [warm-up guidance](../faq.md) explain the serving setup and warm-up. The one-GPU and four-GPU README commands use their default cache settings.
+
+## Contributor fixes
+
+Four tooling fixes in this release come from @kevin9327: `cuda_redist.py` installs CUDA on Python 3.10, wheels without a description keep their added `License-File` headers, the wheel index tool writes its root page before any artifact exists, and `stop_check.py` reports a workload file that is too short before it sends any request. @lunar-me fixed grammar in the FAQ and known limits. Thank you both.
+
+## Limits
+
+The release correctness check compares each EAGLE-4 output with the same engine's output without speculation on the same prompts, and judges every first difference against an fp32 recomputation of that position. Across the four SGLang configurations, 12,089 of 12,096 checked outputs (prompts over starts and concurrency levels) pass. Of the 15 outputs that first fell outside the tolerance, 8 carry a token that plain decoding on the same engine build, recipe and tensor-parallel size also emits at the exact prefix, in a replay batch no larger than the tested concurrency. Numerical thresholds stay unchanged. Seven outputs remain outside the tolerance:
+
+- SGLang README command on one GPU at 128 concurrent requests: one prompt in each of four starts.
+- SGLang measured recipe on four GPUs at 64 concurrent requests: one prompt in each of two starts.
+- SGLang high-load recipe on four GPUs at 512 concurrent requests: one prompt in one start.
+
+The vLLM measured recipe passes its release correctness check. Version 0.1.4 will compare against plain decoding at the same batch size.
+
+On the four-GPU SGLang README command at 8 concurrent requests, 0.1.3 reaches 0.97× the throughput of 0.1.2 (2,549.3 against 2,624.1 output tokens per second, four starts each), below the 0.98× release threshold. The speed measurements cover the model, commands and GPU counts above. SGLang's high-load recipe measures 0.98× plain-decoding throughput at 128 concurrent requests, and some other high-load cells are slightly below 1.00×. This release makes no claim that speculation is faster for every workload.
+
+TokenSpeed static mode (`"mode": "static"`) stops at server start with the released EAGLE-4 draft, whose attention layer uses a 4096-token sliding window. The TokenSpeed 0.1.3 engine has no sliding-window path for draft trees yet. Serve mode runs the draft tree in `eagle-harness` and is the supported TokenSpeed path. Static-mode support is planned for 0.1.4. The [known limits](../known-limits.md) describe the remaining engine and request-feature constraints.
+
+## Files on the release page
+
+Install `eagle-harness` from PyPI. The engine index selects the matching engine wheels from their release assets.
+The source archives are for reading or building the code, not required for installation.
diff --git a/docs/release.env b/docs/release.env
index b2db9aa..52411ba 100644
--- a/docs/release.env
+++ b/docs/release.env
@@ -18,13 +18,13 @@ export EAGLE_SGLANG_IMAGE="$EAGLE_IMAGE_ROOT-sglang:$EAGLE_IMAGE_VERSION"
# Not published yet: build it locally (docs/install.md, "Build the ROCm image").
export EAGLE_ROCM_IMAGE="$EAGLE_IMAGE_ROOT-sglang-rocm:$EAGLE_IMAGE_VERSION"
export EAGLE_VLLM_IMAGE="$EAGLE_IMAGE_ROOT-vllm:$EAGLE_IMAGE_VERSION"
-export EAGLE_TOKENSPEED_IMAGE="$EAGLE_IMAGE_ROOT-tokenspeed:$EAGLE_IMAGE_VERSION"
-export EAGLE_SGLANG_VERSION='0.5.23.dev252+eagle.5'
+export EAGLE_TOKENSPEED_IMAGE="$EAGLE_IMAGE_ROOT-tokenspeed:0.1.3"
+export EAGLE_SGLANG_VERSION='0.5.23.dev252+eagle.9'
export EAGLE_ROCM_VERSION='0.5.23.dev252+eagle.4.rocm'
export EAGLE_VLLM_VERSION='0.32.0rc1.dev283+eagle.4'
-export EAGLE_TOKENSPEED_VERSION='0.1.1+eagle.5'
+export EAGLE_TOKENSPEED_VERSION='0.1.1+eagle.8'
export EAGLE_TORCH_CUDA_INDEX='https://download.pytorch.org/whl/cu130'
# The pinned SGLang dependency cuda-tile==1.6.0rc5 has vendor wheels here.
export EAGLE_NVIDIA_INDEX='https://pypi.nvidia.com'
# These are coupled native packages from the same TokenSpeed release source.
-export EAGLE_TOKENSPEED_AUX_REQUIREMENTS='tokenspeed-scheduler==0.1.40+eagle.4 tokenspeed-kernel==0.1.4+eagle.5'
+export EAGLE_TOKENSPEED_AUX_REQUIREMENTS='tokenspeed-scheduler==0.1.42+eagle.8 tokenspeed-kernel==0.1.4+eagle.8 tokenspeed-engine==0.1.0+eagle.8'
diff --git a/docs/support-matrix.md b/docs/support-matrix.md
index 3f95197..698c731 100644
--- a/docs/support-matrix.md
+++ b/docs/support-matrix.md
@@ -137,7 +137,8 @@ prefix in its checks goes directly to fp32 arbitration.
## 0.1.1 (released)
`eagle-harness` 0.1.1 with `sglang==0.5.23.dev252+eagle.5`, the unchanged `vllm==0.32.0rc1.dev283+eagle.4`, and
-`tokenspeed==0.1.1+eagle.5` with `tokenspeed-kernel==0.1.4+eagle.5` and `tokenspeed-scheduler==0.1.40+eagle.4`.
+the TokenSpeed runtime, kernel and scheduler build shipped for 0.1.1, since withdrawn. These TokenSpeed results
+describe that historical build, not the hooks-only engine shipped for 0.1.3.
The packages are installed from the published wheels into clean environments and served from outside any checkout.
The SGLang ROCm install keeps the 0.1.0 engine and `eagle-harness` 0.1.0 through its hash lock, so the 0.1.0 MI355X
row applies. TP8 and vLLM TP1/TP8 keep their 0.1.0 measurements.
@@ -222,7 +223,8 @@ TokenSpeed in serve mode 6 exact / 8 fp32-tolerance passes / 6 fp32-argmax.
## 0.1.2 (released, current)
`eagle-harness` 0.1.2 with the 0.1.1 engines: `sglang==0.5.23.dev252+eagle.5`, `vllm==0.32.0rc1.dev283+eagle.4`,
-and `tokenspeed==0.1.1+eagle.5` with `tokenspeed-kernel==0.1.4+eagle.5` and `tokenspeed-scheduler==0.1.40+eagle.4`.
+and the unchanged TokenSpeed build measured for 0.1.1, since withdrawn. These TokenSpeed results describe
+that historical build, not the hooks-only engine shipped for 0.1.3.
Every row runs on NVIDIA B300, on the release candidate build of `eagle-harness` 0.1.2 installed into clean
environments with the published engine wheels and served from outside any checkout. In the same allocations, 0.1.2
measured between 0.98× and 1.07× the 0.1.1 packages in every cell where both ran. The SGLang ROCm install keeps its
@@ -238,6 +240,7 @@ measured between 0.98× and 1.07× the 0.1.1 packages in every cell where both r
| vLLM TP4 | ✅ 2.83× | ✅ 1.73× | ⚠️ 1.19× |
| TokenSpeed TP4 | ✅ 3.13× | ✅ 2.00× | ✅ 1.40× |
| TokenSpeed TP4, 32K-token context | ✅ 3.15× | — | — |
+| TokenSpeed TP4, 128K-token context | ✅ 3.37× | — | — |
| TokenSpeed TP1 | ✅ 3.27× | ✅ 2.14× | ✅ 1.35× |
| TokenSpeed TP8 | ✅ 2.91× | ✅ 1.57× | ✅ 1.14× |
| TokenSpeed TP4 chain, temperature 0 | ✅ 2.24× | ✅ 1.65× | ✅ 1.02× |
@@ -269,6 +272,10 @@ Sources:
6. TokenSpeed TP4, 32K: the same server at running cap 4, one 32,768-token prompt with 256 new tokens, a warm
request and 3 measured requests per start, 2 starts per arm. 812.1 against 258.0 decode tokens/s (first to last
streamed token). Every start gives 6 exact / 14 fp32 pass.
+ At 128K the same server takes `--max-model-len 135168` (the only change; 65536 cannot hold the prompt) and one
+ 131,072-token prompt with 256 new tokens, same requests and starts: 801.3 against 237.5 decode tokens/s.
+ Every start returns the same 256 tokens, with and without speculation, and gives 6 exact / 14 fp32 pass on the
+ twenty prompts.
7. TokenSpeed TP1: the TP4 recipe on one GPU with the TP4 cost tables (no TP1 tables exist yet), same workloads
and running caps, 2 starts per arm. 352.5 against 107.9 tokens/s at 1, and 323.4 against 106.9 (3.03×) on eleven
first turns. 1378.8 against 643.3 at 8 and 2620.4 against 1944.7 at 64. Every start passes the twenty-prompt
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 0be6cba..a692eaf 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -55,7 +55,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 |
| `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 |
-| `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 |
+| `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 ([TokenSpeed guide](quickstart-tokenspeed.md#calibrate-costs)) |
| `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 part of the tree shape, or a chain config without one | pass all three, or none of them for the default tree (depth 12, top-k 4, verify width 16) |
@@ -65,9 +65,12 @@ no supported host installed (one of: sglang, vllm, tokenspeed)
| `Unexpected FlashInfer page size 128 without trtllm-gen GQA` (vLLM) | the draft runs on FlashInfer, which serves a multi-head draft only on pages up to 64 tokens; a hybrid target needs 128 or more | set `"attention_backend": "FLASH_ATTN"` in `--speculative-config` (the draft's backend only) |
| `num_speculative_tokens=... disagrees with method_config.max_verify_width=...` (vLLM) | both were set and do not differ by one | set only `max_verify_width` |
| `the draft tree has fewer nodes than the verify width needs; raise tree_depth or node_top_k` (vLLM) | the tree cannot fill the verify width | raise `tree_depth` or `node_top_k`, or lower `max_verify_width` |
-| `EAGLE_HARNESS on TokenSpeed supports static and serve modes` (TokenSpeed) | an unsupported evaluation or calibration mode | use `serve` with matching cost tables for the checked path; static remains unqualified |
+| `EAGLE_HARNESS on TokenSpeed supports static, serve and calibrate modes` (TokenSpeed) | an unsupported evaluation mode | use `serve` for generation, or the [TokenSpeed calibration driver](quickstart-tokenspeed.md#calibrate-costs) to measure costs |
+| `TokenSpeed calibrate mode needs data_path` | calibration has no output directory | run `python -m eagle_harness.tokenspeed.measure_run --help` and choose a fresh `--run-dir` |
+| `batch ... stayed unstable` or missing TokenSpeed measurements | timings did not converge or the requested batch did not stay full | retain the raw timings, check GPU contention and available request/KV capacity, then rerun into a fresh directory |
| `tree drafting topk=... exceeds verify width ...` (TokenSpeed) | a draft step needs more write locations than the verify-sized buffer holds | raise `--speculative-num-draft-tokens` or lower top-k |
| `FlashInferSamplingBackend cannot verify draft trees; use --sampling-backend greedy or triton` (TokenSpeed) | TokenSpeed's default sampling backend | pass `--sampling-backend greedy` |
+| `NotImplementedError: draft trees have no sliding-window or attention-sink path yet` (TokenSpeed) | static mode with a sliding-window draft such as the released EAGLE-4 draft, which the TokenSpeed 0.1.3 engine's own draft trees do not support yet | serve with `"mode": "serve"` and calibrated costs ([TokenSpeed guide](quickstart-tokenspeed.md#calibrate-costs)) |
| `--speculative-num-draft-tokens N verifies more nodes than a tree of depth ... holds` (TokenSpeed) | the tree cannot fill the verify width | raise `--speculative-num-steps` or `--speculative-eagle-topk`, or lower the width |
| `EAGLE-4 drafts with [...] are not ported to eagle-harness yet (dense drafts only).` | a draft structure the engine does not build (see the FAQ, "Which models work?") | use a supported single-layer EAGLE-4 draft |
| `TypeError: int() argument must be ... not 'NoneType'` in `average_context`, on the first request (sglang) | `eagle-harness` 0.1.0 with SGLang's default overlap scheduler | upgrade to `eagle-harness` 0.1.1 or newer, which serves with the overlap scheduler, or pass `--disable-overlap-schedule` |
diff --git a/eagle_harness/core/calibration.py b/eagle_harness/core/calibration.py
index c705aa9..a30672f 100644
--- a/eagle_harness/core/calibration.py
+++ b/eagle_harness/core/calibration.py
@@ -22,7 +22,7 @@ import logging
import os
from collections import defaultdict
from dataclasses import asdict, dataclass
-from typing import Dict, List, Sequence, Tuple
+from typing import Any, Dict, List, Sequence, Tuple
import numpy as np
@@ -455,6 +455,28 @@ class AttentionShape:
sliding_window: int = 0
+def attention_shape(config: Any) -> AttentionShape:
+ """Read attention counts from a text config, refusing unknown layer layouts."""
+ config = getattr(config, "text_config", config)
+ layers = getattr(config, "num_hidden_layers", 0)
+ types = getattr(config, "layer_types", None)
+ window = getattr(config, "sliding_window", None) or 0
+ if types is None:
+ if getattr(config, "full_attention_interval", None) or getattr(config, "hybrid_override_pattern", None):
+ raise ValueError("hybrid calibration needs explicit layer_types in the model config")
+ types = [
+ "sliding_attention" if window and getattr(config, "use_sliding_window", True) else "full_attention"
+ ] * layers
+ known = {"full_attention", "sliding_attention", "linear_attention", "mamba"}
+ if len(types) != layers or set(types) - known:
+ raise ValueError(f"cannot infer attention layout for calibration: {types!r}")
+ count = sum(kind in {"full_attention", "sliding_attention"} for kind in types)
+ sliding = types.count("sliding_attention")
+ if count < 1 or (sliding and window <= 0):
+ raise ValueError("calibration needs attention layers and a positive window for sliding attention")
+ return AttentionShape(count, sliding, window)
+
+
def save_model_timings(paths: CalibrationPaths, params: MeasureParams, records: Sequence[MeasureRecord]) -> None:
"""Group step timings by model and query length into ``model_qo_len_<q>.jsonl``."""
groups: Dict[Tuple[str, int], List[MeasureRecord]] = defaultdict(list)
diff --git a/eagle_harness/core/config.py b/eagle_harness/core/config.py
index b819847..b0191f4 100644
--- a/eagle_harness/core/config.py
+++ b/eagle_harness/core/config.py
@@ -120,11 +120,15 @@ class HarnessConfig:
cost_model: CostModelConfig = field(default_factory=CostModelConfig)
draft_model: DraftModelOptions = field(default_factory=DraftModelOptions)
l2_warm: L2Warm = field(default_factory=L2Warm)
+ # The largest batch that speculates; larger batches decode natively. None: every running batch may speculate.
+ max_verify_batch_size: Optional[int] = None
def validate(self) -> "HarnessConfig":
"""Check the config; return it."""
if self.mode is Mode.CALIBRATE and not self.data_path:
raise ValueError("calibrate mode needs data_path for its output")
+ if self.max_verify_batch_size is not None and self.max_verify_batch_size < 1:
+ raise ValueError("max_verify_batch_size must be at least 1")
return self
@property
diff --git a/eagle_harness/kernels/tree_step.py b/eagle_harness/kernels/tree_step.py
index bf3f06c..3cf0085 100644
--- a/eagle_harness/kernels/tree_step.py
+++ b/eagle_harness/kernels/tree_step.py
@@ -123,7 +123,8 @@ def _tree_step_kernel(
c = tl.arange(0, DELTA_P)[None, :]
e = c - CAP
old = tl.load(best_prev_ptr + b * best_stride + c, mask=c < CAP, other=0.0, cache_modifier=".cg")
- extra = tl.load(layer_top_ptr + b * K + e, mask=(e >= 0) & (e < j), other=0.0, cache_modifier=".cg")
+ # J_P rounds K + 1 up to a power of two: rows j > K are never stored, and must not read past the row's K.
+ extra = tl.load(layer_top_ptr + b * K + e, mask=(e >= 0) & (e < j) & (e < K), other=0.0, cache_modifier=".cg")
sums = tl.cumsum(tl.sort(old + extra, dim=1, descending=True), axis=1)
tl.store(deltas_ptr + b * deltas_stride + c * (K + 1) + j, sums, mask=(j <= K) & (c < V))
diff --git a/eagle_harness/sglang/algorithm.py b/eagle_harness/sglang/algorithm.py
index d874191..29963da 100644
--- a/eagle_harness/sglang/algorithm.py
+++ b/eagle_harness/sglang/algorithm.py
@@ -30,6 +30,7 @@ EAGLE preparation, which allocates them in chunks.
from __future__ import annotations
+import dataclasses
import json
import logging
import os
@@ -42,7 +43,7 @@ from sglang.srt.speculative.spec_registry import CustomSpecAlgo
from eagle_harness.core.config import HarnessConfig, Mode, config_to_dict, parse_harness_config
from eagle_harness.core.cost_profiles import packaged_cost_profile
from eagle_harness.core.gemm_solutions import AITER_GEMM_TABLE, AITER_GEMM_TABLE_ENV, serve_bf16_gemms_through_torch
-from eagle_harness.core.limits import ComputeIntensity, check_shape, req_to_token_span
+from eagle_harness.core.limits import ComputeIntensity, check_shape, max_batch_size, req_to_token_span
from eagle_harness.kernels import arch
if TYPE_CHECKING:
@@ -87,6 +88,20 @@ def _check_rocm_environment(server_args: "ServerArgs") -> None:
)
+def default_batch_limits(config: HarnessConfig, native_route: bool) -> tuple[int, Optional[int]]:
+ """``(max_running_requests, max_verify_batch_size)`` of a server launched without ``--max-running-requests``.
+
+ Speculation verifies at most the memory-conservative default (``max_verify_batch_size``, else 32 for a tree and
+ 48 for a chain). Where larger batches can decode natively (``native_route``), the server admits up to the tree or
+ chain batch limit and the engine lowers that to what its memory holds, as without speculation; otherwise the
+ verify limit is also the admission limit.
+ """
+ verify_rows = config.max_verify_batch_size or (48 if config.intensity is ComputeIntensity.CHAIN else 32)
+ if native_route:
+ return max_batch_size(config.intensity), verify_rows
+ return verify_rows, config.max_verify_batch_size
+
+
def harness_config() -> HarnessConfig:
"""The harness config of this process (``--speculative-algorithm-config``)."""
return parse_harness_config(get_spec().speculative_algorithm_config)
@@ -123,6 +138,11 @@ class EagleHarnessSpecAlgo(CustomSpecAlgo):
return False
# ---- H7: per-width target-verify graphs
+
+ def max_verify_batch_size(self) -> Optional[int]:
+ """The largest batch the harness verifies (``max_verify_batch_size``); it decodes larger batches natively,
+ so a hybrid target keeps verify states for that many requests only."""
+ return self.config.max_verify_batch_size
def create_decode_graph_variants(self, info: "DecodeGraphRunnerInfo") -> Optional["VerifyWidthGraphs"]:
"""H7: one target-verify graph per verify width (and per tree width the greedy graph of a
batch-size-1 round) on the target runner, kept as :attr:`target_verify_graphs`."""
@@ -147,7 +167,11 @@ class EagleHarnessSpecAlgo(CustomSpecAlgo):
and (self.config.mode is Mode.CALIBRATE or any(0 in row for row in (rounds or {}).values()))
) or ((served_chain(self.config, topk) or served_tree(self.config, topk)) and native_decode_available())
self.target_verify_graphs = VerifyWidthGraphs(
- self.config.intensity, max_width, TreeTailMask(info.device), plain_decode=plain
+ self.config.intensity,
+ max_width,
+ TreeTailMask(info.device),
+ plain_decode=plain,
+ max_verify_bs=self.config.max_verify_batch_size,
)
return self.target_verify_graphs
@@ -232,8 +256,19 @@ class EagleHarnessSpecAlgo(CustomSpecAlgo):
server_args.enable_mixed_chunk = False
logger.warning("Mixed chunked prefill is disabled: EAGLE_HARNESS does not take mixed steps.")
if server_args.max_running_requests is None:
- # Keep the memory-conservative default separate from the supported batch limit.
- server_args.max_running_requests = 48 if config.intensity is ComputeIntensity.CHAIN else 32
+ from eagle_harness.sglang.chain_rounds import served_chain, served_tree
+ from eagle_harness.sglang.plain_decode import verify_limit_supported
+
+ topk = server_args.speculative_eagle_topk
+ native_route = (
+ (served_tree(config, topk) or served_chain(config, topk))
+ and server_args.dp_size == 1
+ and verify_limit_supported()
+ )
+ server_args.max_running_requests, verify_rows = default_batch_limits(config, native_route)
+ if verify_rows != config.max_verify_batch_size:
+ config = dataclasses.replace(config, max_verify_batch_size=verify_rows)
+ server_args.speculative_algorithm_config = json.dumps(config_to_dict(config))
topk = server_args.speculative_eagle_topk
check_shape(
config.intensity,
diff --git a/eagle_harness/sglang/calibrate.py b/eagle_harness/sglang/calibrate.py
index a246d3f..013073c 100644
--- a/eagle_harness/sglang/calibrate.py
+++ b/eagle_harness/sglang/calibrate.py
@@ -24,7 +24,8 @@ that ``data_path`` reads them. ``report`` prints the round times per batch size
the widths per batch size that server will use (:func:`eagle_harness.core.chain_width.chain_widths`).
After native decode begins, requests stay OFF until completion because their draft KV is stale. A prefill resets
-the calibration sequence for fresh requests. The runtime requires DP1 and disabled Mamba prefix-cache tracking.
+the calibration sequence for fresh requests. The runtime requires DP1 and, with Mamba prefix-cache tracking, an
+engine whose native decode tracks it.
These are served-path timings on purpose: the period of a served round holds the scheduler, the draft extend and the
launches, which isolated forward timings miss.
diff --git a/eagle_harness/sglang/chain_rounds.py b/eagle_harness/sglang/chain_rounds.py
index f3e5359..9d83b8b 100644
--- a/eagle_harness/sglang/chain_rounds.py
+++ b/eagle_harness/sglang/chain_rounds.py
@@ -60,6 +60,11 @@ BURST_SHARE = 8
# the two measured rates: a wrong native choice costs only the speculative gain, a wrong speculative one runs slower
# than plain decoding.
NATIVE_MARGIN_SE = 2.0
+# A comparison with native decode whose two rates lie within that margin of each other is measured again, up to this
+# many times, before native decode serves by default. Cold-start rounds (first kernel launches, a busy host) can slow
+# speculation's 32 periods a few-fold without any one of them reaching STALL_FACTOR: one inconclusive pass at batch key 1
+# then made a one-GPU server decode natively at every load, and kept that choice across restarts.
+NATIVE_REMEASURES = 2
# Speculation that beats native decode's estimate (the batch's one-token verify in the live costs) by this factor,
# beyond NATIVE_MARGIN_SE standard errors, is not measured against native decode. Requests decoded natively cannot
# resume drafting and a batch holding one decodes natively, so measuring native decode keeps the batch native until it
@@ -277,6 +282,7 @@ class ServedChainPolicy:
self._native = native_decode
self._native_us = native_us
self._native_checked: set = set() # batch keys whose speculation was checked against native decode's estimate
+ self._remeasured: Dict[int, int] = defaultdict(int) # inconclusive native comparisons measured again, per key
self._writer = writer
self._sync = sync
self._path = cache_path
@@ -415,6 +421,13 @@ class ServedChainPolicy:
margin = NATIVE_MARGIN_SE * math.sqrt(best_var + var)
return best if best_rate - rate > margin else 0
+ @staticmethod
+ def _tied(rates: Dict[int, Tuple[float, float]], width: int) -> bool:
+ """Whether speculation at ``width`` and native decode are within :data:`NATIVE_MARGIN_SE` standard errors
+ of each other (neither clearly ahead)."""
+ (spec, spec_var), (native, native_var) = rates.get(width, (0.0, math.inf)), rates.get(0, (0.0, math.inf))
+ return abs(spec - native) <= NATIVE_MARGIN_SE * math.sqrt(spec_var + native_var)
+
def _compare(self, key: int, pair: Tuple[int, int]) -> None:
"""Both widths of the pair have their periods: rank 0 decides the next step, every rank applies it."""
step = None
@@ -430,6 +443,9 @@ class ServedChainPolicy:
step = ("compare", best, self._wider(best))
elif best != 0 and challenger != 0 and self._native and not spec_won_above:
step = ("compare", best, 0)
+ elif challenger == 0 and best == 0 and self._remeasured[key] < NATIVE_REMEASURES and self._tied(rates, pair[0]):
+ self._remeasured[key] += 1
+ step = ("compare", pair[0], 0)
else:
step = ("decide", best, None)
logger.info(
diff --git a/eagle_harness/sglang/draft_kv.py b/eagle_harness/sglang/draft_kv.py
new file mode 100644
index 0000000..19e2799
--- /dev/null
+++ b/eagle_harness/sglang/draft_kv.py
@@ -0,0 +1,138 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Prompt prefills that write only the draft's KV, and which KV slots lack the draft's KV.
+
+A request admitted into a running batch above the verify limit decodes natively for life
+(:class:`~eagle_harness.sglang.plain_decode.NativeDecode`), so of its prompt pass the draft needs only the KV, for
+later requests that reuse the prompt through the prefix cache: :func:`kv_only_prefill` writes it without the
+draft's attention, MLP, head and top-k. :class:`StaleDraftKV` records the slots written by the target alone (native
+decode steps) and counts the drafted prefills that reuse any of them, so drafting over them is known.
+"""
+
+import logging
+from typing import TYPE_CHECKING, Optional
+
+import torch
+
+if TYPE_CHECKING:
+ from sglang.srt.managers.schedule_batch import ScheduleBatch
+ from sglang.srt.managers.tp_worker import TpModelWorker
+
+logger = logging.getLogger(__name__)
+
+
+def kv_only_prefill_supported() -> bool:
+ """Whether the engine binds a draft forward batch to the target prefill's KV write plan (``kv_loc_plan``) and
+ writes KV through ``KVWriteLoc``: the draft KV then lands where its attention would write it."""
+ import inspect
+
+ from sglang.srt.model_executor.forward_batch_info import ForwardBatch
+
+ try:
+ from sglang.srt.mem_cache.memory_pool import KVWriteLoc # noqa: F401
+ except ImportError:
+ return False
+ return "kv_loc_plan" in inspect.signature(ForwardBatch.init_new).parameters
+
+
+def kv_only_prefill(
+ batch: "ScheduleBatch",
+ target_worker: "TpModelWorker",
+ draft_runner,
+ *,
+ topk: int,
+ hidden: "tuple[int, torch.dtype]",
+ on_publish=None,
+ pp_proxy_tensors=None,
+):
+ """The target's prefill, then only the draft's KV of the prompt (the engine's draft prompt pass up to its
+ attention: the same token shift, hidden states and write plan). The next draft input is a placeholder that native
+ decode does not read (it consumes ``bonus_tokens`` only), shaped as the overlap relay stores it. ``hidden``: the
+ draft's recurrent hidden state (size, dtype). The caller enters the draft's TP context."""
+ from sglang.srt.model_executor.forward_batch_info import CaptureHiddenMode, ForwardBatch
+ from sglang.srt.speculative.eagle_info import EagleDraftExtendInput, EagleDraftInput
+ from sglang.srt.speculative.eagle_utils import _eagle_prefill_tail_tokens
+
+ out = target_worker.forward_batch_generation(
+ batch, pp_proxy_tensors=pp_proxy_tensors, capture_hidden_mode=CaptureHiddenMode.FULL, return_kv_loc_plan=True
+ )
+ plan, out.kv_loc_plan = out.kv_loc_plan, None
+ out.new_seq_lens = batch.seq_lens # spec v2: the length before this iteration's tokens, as a drafted prefill
+ if on_publish is not None:
+ on_publish(out.new_seq_lens)
+ tail = _eagle_prefill_tail_tokens(batch, out.next_token_ids)
+ batch.spec_info = EagleDraftExtendInput(
+ hidden_states=out.logits_output.hidden_states, num_tokens_per_req=1, num_tokens_for_logprob_per_req=1
+ )
+ forward_batch = ForwardBatch.init_new(
+ batch, draft_runner, capture_hidden_mode=CaptureHiddenMode.NULL, return_hidden_states_before_norm=False,
+ kv_loc_plan=plan,
+ )
+ # Each position's draft input is the next token: shift every request's ids left, its last one the tail token.
+ ids = torch.roll(forward_batch.input_ids, -1)
+ ids[torch.cumsum(forward_batch.extend_seq_lens, 0) - 1] = tail.to(ids.dtype)
+ forward_batch.input_ids = ids
+ draft_runner.model.write_prefill_kv(forward_batch, draft_runner.token_to_kv_pool)
+ rows, device = len(batch.reqs), out.next_token_ids.device
+ size, dtype = hidden
+ out.next_draft_input = EagleDraftInput(
+ topk_p=torch.zeros((rows, topk), device=device, dtype=torch.float32),
+ topk_index=torch.zeros((rows, topk), device=device, dtype=torch.int64),
+ hidden_states=torch.zeros((rows, size), device=device, dtype=dtype),
+ bonus_tokens=out.next_token_ids,
+ num_tokens_per_req=1,
+ num_tokens_for_logprob_per_req=1,
+ )
+ return out
+
+
+class StaleDraftKV:
+ """Per KV slot: written by the target without the draft (True: native decode) or with it.
+
+ ``window``: the draft's attention window (None: the whole context); a reused slot older than the window of the
+ request's first drafted position is never read and is not counted.
+ """
+
+ LOG_EVERY = 64 # drafted prefills with a reused prefix between two reads of the device counters
+
+ def __init__(self, slots: int, device, window: Optional[int] = None):
+ self.stale = torch.zeros(slots, dtype=torch.bool, device=device)
+ self.window = window
+ self._reused = torch.zeros(2, dtype=torch.int64, device=device) # prefills, stale slots read
+ self._checked = 0
+ self._logged = 0
+
+ # index_fill_, not ``stale[slots] = value``: the item assignment copies the Python value to the device and
+ # waits for the stream (once per decode step).
+ def target_only(self, slots: torch.Tensor) -> None:
+ self.stale.index_fill_(0, slots.long(), True)
+
+ def drafted(self, slots: torch.Tensor) -> None:
+ self.stale.index_fill_(0, slots.long(), False)
+
+ def reused(self, req_to_token: torch.Tensor, rows, prefix_lens, seq_lens) -> None:
+ """Count the stale slots a drafted prefill reads in its requests' cached prefixes (``rows`` / ``prefix_lens``
+ / ``seq_lens`` per request, host values)."""
+ for row, prefix, total in zip(rows, prefix_lens, seq_lens):
+ if prefix <= 0:
+ continue
+ first = 0 if self.window is None else max(0, total - self.window)
+ if first >= prefix:
+ continue
+ stale = self.stale[req_to_token[row, first:prefix].long()].sum()
+ self._reused[0] += (stale > 0).long()
+ self._reused[1] += stale
+ self._checked += 1
+ if self._checked % self.LOG_EVERY == 0:
+ self.log()
+
+ def log(self) -> None:
+ prefills, slots = self._reused.tolist()
+ if prefills != self._logged:
+ self._logged = prefills
+ logger.info(
+ "eagle-harness: %d of %d drafted prefills reused prefix-cache KV without the draft's KV (%d slots: "
+ "prompts prefilled or tokens decoded above the verify limit); their drafts read stale draft KV",
+ prefills, self._checked, slots,
+ )
diff --git a/eagle_harness/sglang/hooks.py b/eagle_harness/sglang/hooks.py
index 744cc2f..7a31b5b 100644
--- a/eagle_harness/sglang/hooks.py
+++ b/eagle_harness/sglang/hooks.py
@@ -113,6 +113,7 @@ HOOKS: tuple[Hook, ...] = (
Hook("sglang.srt.arg_groups.fields.spec:Spec.speculative_algorithm_config", (), FIELD),
# H7 per-width verify graphs, H10 GDN / Mamba2 verify extensions.
Hook(f"{_ALGO}.create_decode_graph_variants", ("info",), OVERRIDE, _HARNESS_ALGO),
+ Hook(f"{_ALGO}.max_verify_batch_size", (), OVERRIDE, _HARNESS_ALGO, optional=True),
Hook(f"{_GRAPH_RUNNER_INFO}.is_draft_worker", (), FIELD),
Hook(f"{_GRAPH_RUNNER_INFO}.device", (), FIELD),
Hook(f"{_ALGO}.create_linear_attn_verify_extension", ("state",), OVERRIDE, _HARNESS_ALGO),
diff --git a/eagle_harness/sglang/models/llama_eagle4.py b/eagle_harness/sglang/models/llama_eagle4.py
index db85338..07efae8 100644
--- a/eagle_harness/sglang/models/llama_eagle4.py
+++ b/eagle_harness/sglang/models/llama_eagle4.py
@@ -46,7 +46,7 @@ from sglang.srt.layers.linear import QKVParallelLinear, ReplicatedLinear, RowPar
from sglang.srt.layers.moe.utils import get_moe_a2a_backend
from sglang.srt.layers.quantization.base_config import QuantizationConfig
from sglang.srt.layers.vocab_parallel_embedding import ParallelLMHead, VocabParallelEmbedding
-from sglang.srt.model_executor.forward_batch_info import ForwardBatch, PPProxyTensors
+from sglang.srt.model_executor.forward_batch_info import ForwardBatch, ForwardMode, PPProxyTensors
from sglang.srt.model_loader.weight_utils import default_weight_loader
from sglang.srt.models.llama import LlamaDecoderLayer, LlamaForCausalLM
from sglang.srt.runtime_context import get_parallel
@@ -142,6 +142,27 @@ def build_latent_moe(config, prefix: str) -> nn.Module:
return NemotronHMoE(latent_moe_config(config), layer_idx=0, quant_config=None, prefix=prefix)
+def prefill_read_rows(forward_batch: ForwardBatch) -> Optional[torch.Tensor]:
+ """The rows a prefill's draft output is read at (each request's last position), or None for every row.
+
+ sglang's logits processor reads a prefill without input logprobs at ``cumsum(extend_seq_lens) - 1``, for the
+ logits and for the hidden state it keeps (capture LAST); the draft KV of every position is written by the
+ attention, before the rows are picked. Other modes, input logprobs and FULL capture read every row.
+ """
+ if forward_batch.forward_mode not in (ForwardMode.EXTEND, ForwardMode.MIXED) or forward_batch.return_logprob:
+ return None
+ if forward_batch.capture_hidden_mode.is_full() or forward_batch.extend_seq_lens is None:
+ return None
+ return torch.cumsum(forward_batch.extend_seq_lens, dim=0) - 1
+
+
+def _rows_in_place(values: torch.Tensor, rows: torch.Tensor, total: int) -> torch.Tensor:
+ """``values`` (one per row index) at their rows of a ``total``-row tensor; the other rows are zero."""
+ out = values.new_zeros((total, values.shape[-1]))
+ out[rows] = values
+ return out
+
+
class Eagle4DecoderLayer(LlamaDecoderLayer):
"""Llama layer whose qkv reads ``concat(normed embed, normed hidden)`` (through ``eh_proj`` with ``attn_norm``)."""
@@ -188,15 +209,26 @@ class Eagle4DecoderLayer(LlamaDecoderLayer):
attn.attn.sliding_window_size = window - 1
def forward(
- self, positions: torch.Tensor, embeds: torch.Tensor, hidden_states: torch.Tensor, forward_batch: ForwardBatch
+ self,
+ positions: torch.Tensor,
+ embeds: torch.Tensor,
+ hidden_states: torch.Tensor,
+ forward_batch: ForwardBatch,
+ rows: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
- """The layer: norm the embeds and the hidden separately, attend over their concat, then the MLP."""
+ """The layer: norm the embeds and the hidden separately, attend over their concat, then the MLP.
+
+ Attention runs on every row (it writes their draft KV); with ``rows`` the rest of the layer runs on those rows
+ only and the outputs have one row per index.
+ """
residual = hidden_states
x = torch.cat([self.input_layernorm(embeds), self.hidden_norm(hidden_states)], dim=-1)
if self.attn_norm:
residual, _ = self.eh_proj(x)
x = self.pre_attention_layernorm(residual)
x = self.self_attn(positions=positions, hidden_states=x, forward_batch=forward_batch)
+ if rows is not None:
+ x, residual = x[rows], residual[rows]
x, residual = self.post_attention_layernorm(x, residual)
x = self.mlp(x)
if self.reduce_mlp:
@@ -281,10 +313,15 @@ class Eagle4Model(nn.Module):
hidden = self._project_target_features(hidden)
if hidden.shape[0] == 0:
return hidden, [hidden]
- mlp_out, residual = self.layers[0](positions, embeds, hidden, forward_batch)
+ rows = prefill_read_rows(forward_batch)
+ mlp_out, residual = self.layers[0](positions, embeds, hidden, forward_batch, rows=rows)
summed = residual + mlp_out
normed = self.norm(summed)
- return normed, [normed if self.norm_output else summed]
+ aux = normed if self.norm_output else summed
+ if rows is not None:
+ normed = _rows_in_place(normed, rows, hidden.shape[0])
+ aux = normed if self.norm_output else _rows_in_place(aux, rows, hidden.shape[0])
+ return normed, [aux]
class LlamaForCausalLMEagle4(LlamaForCausalLM):
@@ -336,6 +373,34 @@ class LlamaForCausalLMEagle4(LlamaForCausalLM):
"built-in" if self._candidate_crossover is None else f"measured ({self._candidate_crossover} scores)",
)
+ def write_prefill_kv(self, forward_batch: ForwardBatch, pool) -> None:
+ """Write the draft KV of a prefill's positions into ``pool`` (the draft runner's) and nothing else: the
+ layer's input and its key/value projections (the qkv weight's k/v rows), RoPE on the keys, then the pool's
+ write door with the batch's write loc, as the attention backend writes it."""
+ from sglang.srt.mem_cache.memory_pool import KVWriteLoc
+
+ model = self.model
+ hidden = forward_batch.spec_info.hidden_states
+ if hidden.shape[-1] != model.hidden_size:
+ hidden = model._project_target_features(hidden)
+ layer = model.layers[0]
+ x = torch.cat([layer.input_layernorm(model._embed(forward_batch.input_ids)), layer.hidden_norm(hidden)], dim=-1)
+ if layer.attn_norm:
+ x = layer.pre_attention_layernorm(layer.eh_proj(x)[0])
+ attn = layer.self_attn
+ k, v = F.linear(x, attn.qkv_proj.weight[attn.q_size :]).split([attn.kv_size, attn.kv_size], dim=-1)
+ # The rotary op rotates query and key in place on CUDA; a one-head query keeps that cheap.
+ _, k = attn.rotary_emb(forward_batch.positions, k.new_empty((k.shape[0], attn.head_dim)), k)
+ radix = attn.attn
+ pool.set_kv_buffer(
+ radix,
+ KVWriteLoc.for_layer(forward_batch, radix),
+ k.view(-1, attn.num_kv_heads, attn.head_dim),
+ v.view(-1, attn.num_kv_heads, attn.head_dim),
+ getattr(radix, "k_scale", None),
+ getattr(radix, "v_scale", None),
+ )
+
def set_embed(self, embed: torch.Tensor) -> None:
"""Share the target's embedding shard, and with ``draft_model.embed_full`` replicate the table on every rank."""
super().set_embed(embed)
diff --git a/eagle_harness/sglang/plain_decode.py b/eagle_harness/sglang/plain_decode.py
index a4ca5a1..bc35489 100644
--- a/eagle_harness/sglang/plain_decode.py
+++ b/eagle_harness/sglang/plain_decode.py
@@ -6,7 +6,7 @@
import copy
import weakref
from collections.abc import Sequence
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Optional
import torch
from sglang.srt.managers.overlap_utils import FutureMap
@@ -23,19 +23,41 @@ if TYPE_CHECKING:
from eagle_harness.sglang.chain_rounds import ChainRounds
+def native_decode_tracks_mamba() -> bool:
+ """Whether the engine's native DECODE graphs save Mamba prefix-cache states, as its no-spec decode does."""
+ from sglang.srt.model_executor.runner.decode_graph_variants import DecodeGraphRunnerInfo
+
+ return "mamba_track" in DecodeGraphRunnerInfo._fields
+
+
+def verify_limit_supported() -> bool:
+ """Whether the engine keeps verify states for a verify batch limit (``max_verify_batch_size``) and can decode
+ the larger batches natively, radix cache or not."""
+ from sglang.srt.speculative.spec_registry import CustomSpecAlgo
+
+ from eagle_harness.sglang.verify_graphs import native_decode_graphs
+
+ return hasattr(CustomSpecAlgo, "max_verify_batch_size") and native_decode_graphs() and native_decode_tracks_mamba()
+
+
def native_decode_available() -> bool:
"""Whether native decode can serve requests that stop drafting: the engine captures native DECODE graphs among
- the speculative graph variants, and neither Mamba prefix-cache tracking nor DP attention needs the draft's state."""
+ the speculative graph variants, they track Mamba prefix-cache states when the radix cache does, and DP attention
+ is off."""
from sglang.srt.runtime_context import get_exec, get_parallel
from eagle_harness.sglang.verify_graphs import native_decode_graphs
- return native_decode_graphs() and not get_exec().mamba.enable_mamba_extra_buffer and get_parallel().dp_size == 1
+ return (
+ native_decode_graphs()
+ and (native_decode_tracks_mamba() or not get_exec().mamba.enable_mamba_extra_buffer)
+ and get_parallel().dp_size == 1
+ )
def native_decode_blocked() -> bool:
- """Whether the engine has native DECODE graphs but this server's settings (Mamba prefix-cache tracking, DP
- attention) keep requests from switching to them."""
+ """Whether the engine has native DECODE graphs but this server's settings (Mamba prefix-cache tracking on an
+ engine whose native graphs do not track, DP attention) keep requests from switching to them."""
from eagle_harness.sglang.verify_graphs import native_decode_graphs
return native_decode_graphs() and not native_decode_available()
@@ -55,6 +77,12 @@ class NoSpecRequests:
self._disabled.update(requests)
return disabled
+ def disable(self, requests: Sequence["Req"]) -> None:
+ self._disabled.update(requests)
+
+ def all_disabled(self, requests: Sequence["Req"]) -> bool:
+ return all(req in self._disabled for req in requests)
+
def publish(self, on_publish, result: "GenerationBatchResult") -> None:
"""Relay a plain decode's lengths, on host too when the host relay reads them there."""
if self.publishes_host_lengths and result.new_seq_lens_cpu is not None:
@@ -77,16 +105,47 @@ class NativeDecode:
rounds: "ChainRounds",
*,
enabled: bool,
+ track_mamba: bool = False,
+ verify_limit: Optional[int] = None,
):
self._target_worker = target_worker
self._req_to_token = req_to_token
self._rounds = rounds
self._requests = NoSpecRequests() if enabled else None
+ self._track_mamba = track_mamba
+ self._verify_limit = verify_limit # larger batches decode natively
+ # 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
+ self._admitted: weakref.WeakSet[Req] = weakref.WeakSet()
+
+ def skips_draft(self, batch: "ScheduleBatch") -> bool:
+ """Whether a prefill's requests join a running batch above the verify limit (or are all off already): they
+ decode natively for life, so they are turned off here and their prompt pass needs only the draft's KV. A
+ chunked request counts once."""
+ if self._requests is None or self._verify_limit is None:
+ return False
+ new = [req for req in batch.reqs if req not in self._admitted]
+ self._admitted.update(new)
+ self._since += len(new)
+ running = len(self._decoding) + self._since
+ if running > self._verify_limit:
+ # Rows that finished in the last decode leave before this prefill joins: after a burst whose last step
+ # finishes 40 rows, the next lone request would otherwise decode natively for life.
+ running = sum(not req.finished() for req in self._decoding) + self._since
+ skip = running > self._verify_limit or self._requests.all_disabled(batch.reqs)
+ if skip:
+ self._requests.disable(batch.reqs)
+ return skip
def select(self, batch: "ScheduleBatch") -> bool:
if self._requests is None or batch.forward_mode.is_idle():
return False
- return self._requests.select(batch.reqs, self._rounds.plain_width(len(batch.reqs)))
+ bs = len(batch.reqs)
+ self._decoding, self._since = tuple(batch.reqs), 0
+ if self._verify_limit is not None and bs > self._verify_limit:
+ return self._requests.select(batch.reqs, 0)
+ return self._requests.select(batch.reqs, self._rounds.plain_width(bs))
def publish(self, on_publish, result: "GenerationBatchResult") -> None:
"""Publish native lengths through the host-compatible relay."""
@@ -97,17 +156,18 @@ class NativeDecode:
if grammar_barrier is not None:
grammar_barrier()
self._rounds.round_start(len(batch.reqs), 0, batch)
- return plain_decode(batch, self._target_worker, self._req_to_token)
+ return plain_decode(batch, self._target_worker, self._req_to_token, track_mamba=self._track_mamba)
def plain_decode(
- batch: "ScheduleBatch", target_worker: "TpModelWorker", req_to_token: torch.Tensor
+ batch: "ScheduleBatch", target_worker: "TpModelWorker", req_to_token: torch.Tensor, *, track_mamba: bool = False
) -> "GenerationBatchResult":
"""Consume the bonus token in the already-reserved EAGLE KV slot.
The scheduler has already reserved KV, accumulated penalties, and advanced
request decode counters. Repeating its ordinary decode preparation would
- allocate twice. The caller must never resume drafting from the carried state.
+ allocate twice. The caller must never resume drafting from the carried state. ``track_mamba``: the server
+ tracks Mamba prefix-cache states (the radix cache on a hybrid target).
"""
draft_input = batch.spec_info
algorithm = batch.spec_algorithm
@@ -117,6 +177,8 @@ def plain_decode(
if batch.seq_lens_cpu is not None:
batch.seq_lens_cpu = batch.seq_lens_cpu + 1
batch.seq_lens_sum = None
+ if track_mamba:
+ track_mamba_states(batch)
batch.spec_info = None
batch.spec_algorithm = SpeculativeAlgorithm.NONE
batch.forward_mode = ForwardMode.DECODE
@@ -137,3 +199,14 @@ def plain_decode(
result.next_draft_input = copy.copy(draft_input)
result.next_draft_input.bonus_tokens = result.next_token_ids
return result
+
+
+def track_mamba_states(batch: "ScheduleBatch") -> None:
+ """Save the Mamba state of every row whose new length lands on the prefix-cache track grid, as a no-spec decode
+ does (``ScheduleBatch.prepare_for_decode``). The track slots are the ones the speculative round planned, and the
+ result processor records a one-token round's grid crossing like a verify's."""
+ from sglang.srt.runtime_context import mamba_track_grid
+ from sglang.srt.speculative.spec_utils import prepare_mamba_track_for_verify
+
+ prepare_mamba_track_for_verify(batch)
+ batch.mamba_track_mask = batch.seq_lens % mamba_track_grid(batch.tree_cache.page_size) == 0
diff --git a/eagle_harness/sglang/verify_graphs.py b/eagle_harness/sglang/verify_graphs.py
index ad64d95..0376a45 100644
--- a/eagle_harness/sglang/verify_graphs.py
+++ b/eagle_harness/sglang/verify_graphs.py
@@ -60,8 +60,12 @@ class VerifyWidthGraphs(DecodeGraphVariants):
greedy: bool = True,
*,
plain_decode: bool = False,
+ max_verify_bs: Optional[int] = None,
):
+ """``max_verify_bs``: the largest batch that verifies (``max_verify_batch_size``); larger batches capture the
+ native decode graph only."""
self.intensity = intensity
+ self.max_verify_bs = max_verify_bs
self.max_width = max_width
self.tail_mask = tail_mask
self.greedy = greedy
@@ -80,6 +84,8 @@ class VerifyWidthGraphs(DecodeGraphVariants):
def capture_variants(self, bs: int) -> Sequence[DecodeGraphVariant]:
"""The verify-width graphs to capture for a batch size (the argmax graphs last)."""
+ if self.max_verify_bs is not None and bs > self.max_verify_bs:
+ return [self._plain] if self._plain is not None else []
widths = verify_widths(bs, self.intensity, self.max_width)
variants = [self._variant(w) for w in widths]
if self.greedy and bs == 1:
diff --git a/eagle_harness/sglang/worker.py b/eagle_harness/sglang/worker.py
index 8b9163d..44da252 100644
--- a/eagle_harness/sglang/worker.py
+++ b/eagle_harness/sglang/worker.py
@@ -50,6 +50,7 @@ from sglang.srt.model_executor.cuda_graph_config import Backend, Phase, check_cu
from sglang.srt.model_executor.runner import get_batch_sizes_to_capture
from sglang.srt.runtime_context import get_exec, get_model, get_parallel, get_schedule, get_spec
from sglang.srt.speculative.draft_utils import DraftBackendFactory
+from sglang.srt.model_executor.forward_batch_info import ForwardMode
from sglang.srt.speculative.eagle_utils import default_tree_mask_mode
from sglang.srt.speculative.eagle_worker_common import run_eagle_verify
from sglang.srt.speculative.eagle_worker_v2 import EagleDraftWorker, EAGLEWorkerV2
@@ -77,9 +78,15 @@ from eagle_harness.core.live_costs import CostKey, LiveCosts, config_digest
from eagle_harness.core.gemm_solutions import load_gemm_solutions
from eagle_harness.sglang.draft_extend import DraftExtend
from eagle_harness.sglang.draft_steps import DraftSteps
+from eagle_harness.sglang.draft_kv import StaleDraftKV, kv_only_prefill, kv_only_prefill_supported
from eagle_harness.sglang.drafter import DynamicDrafter, PrelaunchResult, spin_wait
from eagle_harness.sglang.l2_warm import MlpL2WarmAhead
-from eagle_harness.sglang.plain_decode import NativeDecode, native_decode_available, native_decode_blocked
+from eagle_harness.sglang.plain_decode import (
+ NativeDecode,
+ native_decode_available,
+ native_decode_blocked,
+ native_decode_tracks_mamba,
+)
from eagle_harness.sglang.row_attention import DraftRowAttention
from eagle_harness.sglang.verify_step import (
AcceptTailGraphs,
@@ -148,8 +155,13 @@ class HarnessDraftWorker(EagleDraftWorker):
steps: DraftSteps
extend: DraftExtend
- def __init__(self, server_args, gpu_id, nccl_port, target_worker, *, policy: Policy):
+ def __init__(
+ self, server_args, gpu_id, nccl_port, target_worker, *, policy: Policy, max_verify_bs: Optional[int] = None
+ ):
+ """``max_verify_bs``: the largest batch that speculates (``max_verify_batch_size``); the draft buffers and
+ graphs cover it, larger batches decode natively. None: every running batch."""
# Read by init_attention_backend, which sglang's __init__ calls.
+ self._max_verify_bs = max_verify_bs
self._intensity = policy.intensity
self._verify_budget = policy.max_history_verify_num
self._delta_slots = policy.launch_depths
@@ -162,7 +174,7 @@ class HarnessDraftWorker(EagleDraftWorker):
if self.draft_extend_attn_backend is not None:
self.draft_runner.attn_backend = self.draft_extend_attn_backend
model = self.draft_runner.model
- max_bs = get_schedule().max_running_requests
+ max_bs = min(get_schedule().max_running_requests, self._max_verify_bs or get_schedule().max_running_requests)
width = self.speculative_num_draft_tokens
shape = TreeShape(top_k=self.topk, max_depth=self.speculative_num_steps)
device = torch.device(self.device)
@@ -220,6 +232,7 @@ class HarnessDraftWorker(EagleDraftWorker):
if check_cuda_graph_backend(Phase.DECODE, Backend.DISABLED):
return
capture_bs, _ = get_batch_sizes_to_capture(self.draft_runner)
+ capture_bs = [bs for bs in capture_bs if bs <= self.tree.max_bs]
self.steps.capture(capture_bs)
self.extend.capture(capture_bs)
@@ -243,6 +256,9 @@ class EagleHarnessWorker(EAGLEWorkerV2):
(:class:`~eagle_harness.core.live_costs.LiveCosts`) and cache them under ``cost_cache``.
"""
+ _stale_kv: Optional[StaleDraftKV] = None # with a verify limit: slots that lack the draft's KV
+ _kv_only_prefill = False
+
def __init__(self, server_args: "ServerArgs", gpu_id: int, nccl_port: int, target_worker: "TpModelWorker"):
spec = get_spec()
self.config: HarnessConfig = parse_harness_config(spec.speculative_algorithm_config)
@@ -259,16 +275,28 @@ class EagleHarnessWorker(EAGLEWorkerV2):
if served_tree(self.config, spec.speculative_eagle_topk) and native_decode_blocked():
logger.warning(
"EAGLE_HARNESS: this server cannot switch to native decode where speculation loses (Mamba prefix-cache "
- "tracking or DP attention), so it speculates at every load; --disable-radix-cache enables the switch."
+ "tracking on an engine whose native decode does not track it, or DP attention), so it speculates at every "
+ "load."
)
native_decode = self.config.mode is Mode.CALIBRATE or any(
width == 0 for _, _, width in (self._chain_schedule or ())
)
- if native_decode and (get_exec().mamba.enable_mamba_extra_buffer or get_parallel().dp_size != 1):
- raise ValueError("Native no-spec fallback requires DP1 and disabled Mamba prefix-cache tracking.")
+ if native_decode and (
+ (get_exec().mamba.enable_mamba_extra_buffer and not native_decode_tracks_mamba())
+ or get_parallel().dp_size != 1
+ ):
+ raise ValueError(
+ "Native no-spec fallback requires DP1 and, with Mamba prefix-cache tracking, an engine whose native "
+ "decode tracks it."
+ )
self._native_decode_enabled = (
native_decode or self._served_tree or (self._served_chain and native_decode_available())
)
+ if self.config.max_verify_batch_size is not None and not self._native_decode_enabled:
+ raise ValueError(
+ "EAGLE_HARNESS: max_verify_batch_size needs native decode for the larger batches (a serve-mode tree "
+ "or served chain, DP1, and an engine whose native decode tracks Mamba prefix-cache states)."
+ )
self.fixed = FixedShapePolicy(self.config.intensity, **shape)
# Built before sglang's __init__, which creates the draft worker through create_draft_worker.
self.cost_model: Optional[CostModel] = None
@@ -347,7 +375,12 @@ class EagleHarnessWorker(EAGLEWorkerV2):
def create_draft_worker(self, server_args, gpu_id, nccl_port, target_worker) -> HarnessDraftWorker:
"""sglang's EAGLE draft worker with the harness's decode-time draft forwards."""
return HarnessDraftWorker(
- server_args, gpu_id, nccl_port, target_worker, policy=self.cost_model or self.fixed
+ server_args,
+ gpu_id,
+ nccl_port,
+ target_worker,
+ policy=self.cost_model or self.fixed,
+ max_verify_bs=self.config.max_verify_batch_size,
)
def init_attention_backends(self) -> None:
@@ -426,7 +459,59 @@ class EagleHarnessWorker(EAGLEWorkerV2):
self.req_to_token_pool.req_to_token,
self._chain_rounds,
enabled=self._native_decode_enabled,
+ track_mamba=get_exec().mamba.enable_mamba_extra_buffer,
+ verify_limit=self.config.max_verify_batch_size,
+ )
+ if self.config.max_verify_batch_size is not None and self._native_decode_enabled:
+ alloc = self.token_to_kv_pool_allocator
+ model = self._draft_worker.draft_runner.model
+ self._stale_kv = StaleDraftKV(
+ alloc.size + alloc.page_size, torch.device(self.device), window=getattr(model, "window", None)
+ )
+ qkv = model.model.layers[0].self_attn.qkv_proj if hasattr(model, "write_prefill_kv") else None
+ # The draft-KV-only prompt pass slices the qkv weight: an unquantized draft on an engine with write plans.
+ self._kv_only_prefill = (
+ qkv is not None
+ and qkv.weight.dtype in (torch.bfloat16, torch.float16, torch.float32)
+ and kv_only_prefill_supported()
+ )
+ logger.info("eagle-harness: draft-KV-only prompt pass above the verify limit: %s", self._kv_only_prefill)
+
+ def _prefill(self, batch: "ScheduleBatch", on_publish, grammar_barrier, pp_proxy_tensors):
+ """sglang's prefill (target, then the draft's prompt pass), or for requests that join a running batch above
+ the verify limit (they decode natively for life) the target and only the draft's KV. Both write the draft KV
+ of every prompt position, so a later request that reuses the prompt drafts over valid KV."""
+ stale = self._stale_kv
+ if stale is None or batch.forward_mode != ForwardMode.EXTEND or batch.is_extend_in_batch:
+ return super().forward_batch_generation(batch, on_publish, grammar_barrier, pp_proxy_tensors)
+ stale.drafted(batch.out_cache_loc)
+ if (
+ self._kv_only_prefill
+ and not batch.return_hidden_states
+ and all(req.multimodal_inputs is None for req in batch.reqs)
+ and self._native_decode.skips_draft(batch)
+ ):
+ from sglang.srt.speculative.eagle_utils import get_draft_recurrent_hidden_state_spec
+
+ runner = self._draft_worker.draft_runner
+ with self._draft_context():
+ return kv_only_prefill(
+ batch,
+ self.target_worker,
+ runner,
+ topk=self.topk,
+ hidden=get_draft_recurrent_hidden_state_spec(runner),
+ on_publish=on_publish,
+ pp_proxy_tensors=pp_proxy_tensors,
+ )
+ rows = batch.req_pool_indices_cpu # newer engines keep the rows on host; older ones on each request
+ stale.reused(
+ self.req_to_token_pool.req_to_token,
+ rows.tolist() if rows is not None else [req.req_pool_idx for req in batch.reqs],
+ batch.prefix_lens,
+ [prefix + extend for prefix, extend in zip(batch.prefix_lens, batch.extend_lens)],
)
+ return super().forward_batch_generation(batch, on_publish, grammar_barrier, pp_proxy_tensors)
def _save_live_costs(self) -> None:
try:
@@ -446,11 +531,13 @@ 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)
- return super().forward_batch_generation(batch, on_publish, grammar_barrier, pp_proxy_tensors)
+ return self._prefill(batch, on_publish, grammar_barrier, pp_proxy_tensors)
native_decode = self._native_decode.select(batch)
if native_decode:
self._drafter.cancel_prelaunch()
result = self._native_decode.run(batch, grammar_barrier)
+ if self._stale_kv is not None:
+ self._stale_kv.target_only(batch.out_cache_loc)
self._verified.record()
else:
sampled = _sampled_tree(self)
@@ -485,6 +572,8 @@ class EagleHarnessWorker(EAGLEWorkerV2):
with spec_stage_span("verify"):
started = None if timer is None else timer.start()
result, staged = self._verify(batch, width, grammar_barrier)
+ if self._stale_kv is not None and not batch.forward_mode.is_idle():
+ self._stale_kv.drafted(batch.out_cache_loc) # the round's slots; the draft extend writes them
self._verified.record()
if started is not None:
timer.stop(started, self._drafter.bucket(len(batch.reqs)), width, self._drafter.average_context(batch))
diff --git a/eagle_harness/tokenspeed/attention_measurement.py b/eagle_harness/tokenspeed/attention_measurement.py
new file mode 100644
index 0000000..3d29844
--- /dev/null
+++ b/eagle_harness/tokenspeed/attention_measurement.py
@@ -0,0 +1,142 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""TokenSpeed tree-cascade attention timings for calibration."""
+
+from __future__ import annotations
+
+import math
+
+import torch
+from tokenspeed_kernel.ops.attention.mha.flashinfer import trtllm_batch_decode_with_kv_cache
+from tokenspeed_kernel.ops.attention.tree import tree_window_attention
+from tokenspeed.runtime.layers.attention.backends.paged.trtllm import canonicalize_stride
+from tokenspeed.runtime.layers.attention.kernel_page_sizes import TRTLLM_MHA_PAGE_SIZE
+
+from eagle_harness.core.calibration import MeasureRecord
+
+_WORKSPACE_BYTES = 256 << 20
+
+
+def attention_samples(
+ *,
+ batch_size: int,
+ rows: int,
+ window: int,
+ num_q_heads: int,
+ num_kv_heads: int,
+ head_dim: int,
+ sliding_window: int,
+ context_step: int,
+ context_stop: int,
+ fast: bool,
+ repeat: int,
+ widths: list[int],
+ category: str,
+) -> list[MeasureRecord]:
+ """One attention layer of the decode tree cascade over the context range:
+ ``rows`` query rows per request against its ``kv_len``-key prefix (the
+ trtllm-gen decode; a sliding window decodes each row alone over the
+ window ending there) plus its ``window``-key tree window.
+
+ Serving forwards all ``rows`` whatever the round's width, so one timing
+ per context stands for every swept width.
+
+ Returns:
+ A sample per (context, width): microseconds over ``repeat`` layers.
+ """
+ device = torch.device("cuda")
+ dtype = torch.bfloat16
+ page = TRTLLM_MHA_PAGE_SIZE
+ interval = context_step // (16 if fast else 32)
+ lengths = [
+ kv for kv in range(context_step // 2, context_stop + 1, interval)
+ if kv >= context_step
+ ] # fmt: skip
+ pages_per_req = math.ceil((context_stop + window) / page)
+ num_pages = batch_size * pages_per_req
+ k_rows = torch.randn(
+ (num_pages * page, num_kv_heads, head_dim), device=device, dtype=dtype
+ )
+ v_rows = torch.randn_like(k_rows)
+
+ def paged(rows_: torch.Tensor) -> torch.Tensor:
+ cache = rows_.view(-1, page, num_kv_heads, head_dim).permute(0, 2, 1, 3)
+ return canonicalize_stride(cache) if num_kv_heads == 1 else cache
+
+ k_cache, v_cache = paged(k_rows), paged(v_rows)
+ page_table = torch.arange(num_pages, device=device, dtype=torch.int32).view(
+ batch_size, pages_per_req
+ )
+ q = torch.randn(
+ (batch_size * rows, num_q_heads, head_dim), device=device, dtype=dtype
+ )
+ workspace = torch.zeros(_WORKSPACE_BYTES, dtype=torch.uint8, device=device)
+ scale = head_dim**-0.5
+ causal = sliding_window <= 0
+ # Row r sees its path's window keys: a chain for verify rows, one ancestor per depth for lanes.
+ if causal:
+ bits = [(1 << (r + 1)) - 1 for r in range(rows)]
+ else:
+ bits = [
+ sum(1 << (d * rows + r) for d in range(window // rows)) for r in range(rows)
+ ]
+ # Window key j is bit j % 64 of the row's word j // 64; bit 63 is the sign.
+ words = [
+ (b >> (64 * w)) & ((1 << 64) - 1)
+ for b in bits
+ for w in range((window + 63) // 64)
+ ]
+ mask = torch.tensor(
+ [x - (1 << 64) if x >= 1 << 63 else x for x in words] * batch_size,
+ dtype=torch.int64,
+ device=device,
+ )
+ samples = []
+ for kv_len in lengths:
+ prefix = torch.full((batch_size,), kv_len, dtype=torch.int32, device=device)
+ seq_lens = prefix + window
+ if causal:
+ tables, prefix_lens, q_len = page_table, prefix, rows
+ else:
+ tables = page_table.repeat_interleave(rows, dim=0)
+ prefix_lens, q_len = prefix.repeat_interleave(rows), 1
+
+ def layer() -> torch.Tensor:
+ out, lse = trtllm_batch_decode_with_kv_cache(
+ query=q,
+ kv_cache=(k_cache, v_cache),
+ workspace_buffer=workspace,
+ block_tables=tables,
+ seq_lens=prefix_lens,
+ max_seq_len=context_stop + window,
+ bmm1_scale=scale,
+ bmm2_scale=1.0,
+ out_dtype=dtype,
+ q_len_per_req=q_len,
+ window_left=-1 if causal else sliding_window - 1,
+ return_lse=True,
+ )
+ return tree_window_attention(
+ q, k_rows, v_rows, page_table, seq_lens, mask, out, lse,
+ rows_per_req=rows, window=window, causal_prefix=causal,
+ page_size=page, sm_scale=scale,
+ ) # fmt: skip
+
+ layer()
+ graph = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(graph):
+ for _ in range(repeat):
+ layer()
+ start = torch.cuda.Event(enable_timing=True)
+ end = torch.cuda.Event(enable_timing=True)
+ start.record()
+ graph.replay()
+ end.record()
+ end.synchronize()
+ elapsed = max(int(start.elapsed_time(end) * 1000), 1)
+ samples += [
+ MeasureRecord(elapsed, repeat, width, kv_len, category, batch_size)
+ for width in widths
+ ]
+ return samples
diff --git a/eagle_harness/tokenspeed/config.py b/eagle_harness/tokenspeed/config.py
index 4b9d5a7..f91b9e9 100644
--- a/eagle_harness/tokenspeed/config.py
+++ b/eagle_harness/tokenspeed/config.py
@@ -30,6 +30,7 @@ class TokenSpeedConfig(HarnessConfig):
"""Core policy settings plus an optional explicit per-batch chain schedule."""
chain_width_table: tuple[tuple[int, int], ...] = ()
+ sampled_proposals: bool = False
@property
def fully_scheduled(self) -> bool:
@@ -41,6 +42,9 @@ def parse_algorithm_config(algorithm_config: Mapping[str, Any] | None) -> TokenS
"""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 {})
+ sampled = values.pop("sampled_proposals", False)
+ if type(sampled) is not bool:
+ raise ValueError("sampled_proposals must be a boolean") # noqa: TRY004 — configuration validation
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
@@ -57,9 +61,13 @@ def parse_algorithm_config(algorithm_config: Mapping[str, Any] | None) -> TokenS
entries.append(tuple(entry))
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 config.mode not in (Mode.STATIC, Mode.SERVE):
- raise NotImplementedError(f"{ALGORITHM_NAME} on TokenSpeed supports static and serve modes")
+ chain_width_table=tuple(entries), sampled_proposals=sampled)
+ if sampled and config.mode is not Mode.SERVE:
+ raise ValueError("sampled_proposals requires serve mode")
+ if config.mode not in (Mode.STATIC, Mode.SERVE, Mode.CALIBRATE):
+ raise NotImplementedError(f"{ALGORITHM_NAME} on TokenSpeed supports static, serve and calibrate modes")
+ if config.mode is Mode.CALIBRATE and not config.data_path:
+ raise ValueError("TokenSpeed calibrate mode needs data_path")
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:
diff --git a/eagle_harness/tokenspeed/drafter.py b/eagle_harness/tokenspeed/drafter.py
index 73b5d4d..36f15e9 100644
--- a/eagle_harness/tokenspeed/drafter.py
+++ b/eagle_harness/tokenspeed/drafter.py
@@ -16,7 +16,7 @@ of TokenSpeed's:
window and parents TokenSpeed verifies with its own tree attention and GDN tree verify.
Static rounds use Eagle's complete graph. Serve rounds delegate chain/tree execution, fixed-ahead sampled-depth
-planning and recorded-q rejection to the engine. Cost decisions come only from eagle_harness.core; native EAGLE-3
+planning and recorded-q rejection to the harness. Cost decisions come only from eagle_harness.core; native EAGLE-3
and reduced-vocabulary maps stay owned by TokenSpeed.
"""
@@ -27,8 +27,6 @@ from dataclasses import replace
from typing import Any
import torch
-from tokenspeed.runtime.execution.drafter.tree_round.device_policy import DevicePolicy
-from tokenspeed.runtime.execution.drafter.tree_round.dynamic import DynamicDrafter
from tokenspeed.runtime.models.llama_eagle3 import LlamaForCausalLMEagle3
from typing_extensions import override
@@ -38,13 +36,14 @@ from eagle_harness.core.limits import ComputeIntensity
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
from eagle_harness.tokenspeed.tree_lanes import verify_window as fill_verify_window
+from eagle_harness.tokenspeed.tree_round.device_policy import DevicePolicy
+from eagle_harness.tokenspeed.tree_round.dynamic import DynamicDrafter
-# TokenSpeed's own candidate ranking, under the installed engine's name (see hooks.tree_policy).
-_ENGINE_CANDIDATES = getattr(DynamicDrafter, tree_policy().candidates)
+# The harness round executor ranks ordinary EAGLE-3 logits.
+_ENGINE_CANDIDATES = DynamicDrafter.round_candidates
class HarnessDrafter(DynamicDrafter):
@@ -59,6 +58,7 @@ class HarnessDrafter(DynamicDrafter):
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
+ self.measurement = None
def configure_algorithm(self, algorithm_config: Mapping[str, Any]) -> None:
self.config = parse_algorithm_config(algorithm_config)
@@ -74,9 +74,27 @@ class HarnessDrafter(DynamicDrafter):
@property
def dynamic(self) -> bool:
- return self.config is not None and self.config.mode is Mode.SERVE
+ return self.config is not None and self.config.mode in (Mode.SERVE, Mode.CALIBRATE)
def _make_policy(self, verify_num: int, topk: int, depth: int) -> DevicePolicy:
+ if self.config.mode is Mode.CALIBRATE:
+ from tokenspeed.runtime.distributed.process_group_manager import process_group_manager
+
+ from eagle_harness.tokenspeed.measurement import CostMeasurement, MeasurePolicy
+
+ mapping = self.draft_model_runner.mapping
+ self.measurement = CostMeasurement(
+ run_dir=self.config.data_path,
+ tree_depth=depth,
+ tp_group=(process_group_manager.get_device_process_group(mapping.attn.tp_group)
+ if mapping.attn.tp_size > 1 else None),
+ rank=mapping.rank,
+ device=self.device,
+ )
+ return MeasurePolicy(
+ verify_num=verify_num, node_top_k=topk, tree_depth=depth,
+ compute_intensity=self.config.intensity.value, device=self.device,
+ )
model = None if self.config.fully_scheduled else build_cost_model(
self.config,
node_top_k=topk,
@@ -103,18 +121,18 @@ class HarnessDrafter(DynamicDrafter):
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._sampling_backend.config.enable_speculative_sampling:
+ raise ValueError("Use sampled_proposals in --speculative-algorithm-config, not --enable-speculative-sampling")
if self.dynamic:
shape = tree_spec.config
self.bind_dynamic_tree(tree_spec, self._make_policy(shape.num_nodes, shape.topk, shape.num_steps))
- if self._sampling_backend.config.enable_speculative_sampling:
+ if self.config.sampled_proposals:
self.enable_sampled_trees(
num_candidates=(self.draft_model.num_candidates if isinstance(self.draft_model, LlamaForCausalLMEagle4)
else min(1024, getattr(self.draft_model.config, "draft_vocab_size", None) or self.draft_model.config.vocab_size)),
seed=self._sampling_backend.config.random_seed,
)
return
- if self._sampling_backend.config.enable_speculative_sampling:
- raise ValueError("recorded-q proposals require serve mode; static trees support target sampling")
super().bind_tree(tree_spec)
config = tree_spec.config
if config.num_steps < 2:
@@ -145,6 +163,49 @@ class HarnessDrafter(DynamicDrafter):
return super().run(base_ctx, logits_output, output_tokens, accept_lengths)
# ------------------------------------------------------------------ the tree policy
+ def prepare_target_forward(self, ctx: Any) -> None:
+ super().prepare_target_forward(ctx)
+ if self.measurement is not None and ctx.num_extends == 0:
+ self.measurement.verify_start.record()
+
+ def rewrite_verify_outputs(self, ctx: Any, output_tokens: torch.Tensor, accept_lengths: torch.Tensor) -> None:
+ """Calibration commits one fixed token so context grows by one each round."""
+ if self.measurement is None or ctx.num_extends > 0:
+ return
+ self.measurement.verify_end.record()
+ rows, width = accept_lengths.shape[0], self.spec_num_tokens
+ accept_lengths.fill_(1)
+ output_tokens.view(rows, width)[:, 0].copy_(self.measurement.commit_token.expand(rows))
+ path = self._sampling_backend.accepted_path(rows, width)
+ path[:, 0].zero_()
+ path[:, 1:].fill_(-1)
+
+ def has_round_graphs(self, graph_bs: int) -> bool:
+ return self.measurement is None and super().has_round_graphs(graph_bs)
+
+ def finish_round(self, ctx: Any, graph_bs: int | None) -> None:
+ measurement = self.measurement
+ if measurement is None or ctx.bs == 0 or self.input_buffers.all_extends_mid_chunk:
+ return super().finish_round(ctx, graph_bs)
+ from tokenspeed.runtime.utils.host_sync import allow_host_sync
+
+ with allow_host_sync("calibration measures between drained GPUs"):
+ if ctx.num_extends > 0:
+ measurement.on_extend()
+ self.policy.write_full_round()
+ return super().finish_round(ctx, graph_bs)
+ measurement.record_verify(ctx.bs)
+ cache_len = int(self._round["frontier"][:ctx.bs].sum()) // ctx.bs
+ if measurement.measured_batch_size is not None:
+ self.policy.next_widths(ctx.bs, measurement.measured_batch_size)
+ self.policy.write_round()
+ measurement.begin_draft()
+ super().finish_round(ctx, graph_bs)
+ with torch.cuda.stream(self._round_stream):
+ measurement.end_draft(ctx.bs, self.policy.draft_width, self.policy.verify_width_now, cache_len)
+ if measurement.complete():
+ measurement.write_model_records()
+
# 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]:
diff --git a/eagle_harness/tokenspeed/hooks.py b/eagle_harness/tokenspeed/hooks.py
index 55626da..d1d8dd4 100644
--- a/eagle_harness/tokenspeed/hooks.py
+++ b/eagle_harness/tokenspeed/hooks.py
@@ -20,7 +20,8 @@ Two TokenSpeed lines carry the hooks, told apart by :func:`contract`:
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.
+:class:`~eagle_harness.tokenspeed.drafter.HarnessDrafter` replaces. The harness owns the dynamic tree and device policy.
+Recorded-proposal verification is checked separately when sampled trees are enabled.
"""
from __future__ import annotations
@@ -40,8 +41,7 @@ REQUIRED_CAPABILITIES = frozenset(
"drafter.round_protocol",
"drafter.tree_lanes",
"drafter.tree_policy",
- "drafter.dynamic_tree",
- "drafter.sampled_trees",
+ "sampling.tree_sampler",
}
)
@@ -63,13 +63,11 @@ class TreePolicy(NamedTuple):
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")),
@@ -78,6 +76,8 @@ def _policy_hooks(names: TreePolicy) -> tuple[Hook, ...]:
HOOKS: tuple[Hook, ...] = (
Hook("tokenspeed.runtime.plugins:PLUGIN_API_VERSION"),
+ Hook("tokenspeed.runtime.sampling.backends.base:SamplingBackend.bind_tree_sampler", ("factory",)),
+ Hook("tokenspeed.runtime.sampling.backends.base:SamplingBackend.supports_tree_sampler"),
Hook(
"tokenspeed.runtime.plugins.registry:register_drafter",
("algorithm", "drafter_cls", "model_cls", "captures_aux_hidden_states", "uses_tree_layout"),
@@ -88,9 +88,7 @@ HOOKS: tuple[Hook, ...] = (
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.prepare_round_sampling", ("sampling_params_list",)),
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")),
Hook("tokenspeed.runtime.execution.drafter.base:BaseDrafter.complete_round", ()),
@@ -117,6 +115,20 @@ RELEASE_HOOKS: tuple[Hook, ...] = (
)
+SAMPLED_HOOKS = (
+ Hook("tokenspeed.runtime.sampling.tree_verify:DraftTreeQ.zeros", ("rows", "num_slots", "num_candidates", "num_nodes", "device")),
+ Hook("tokenspeed.runtime.sampling.tree_verify:TreeVerifyBatch.draft_q"),
+ Hook("tokenspeed.runtime.execution.runtime_states:RuntimeStates.init_draft_tree_q", ("num_nodes", "num_slots", "num_candidates")),
+ Hook("tokenspeed.runtime.sampling.backends.base:SamplingBackend.verifies_draft_tree_q"),
+ Hook("tokenspeed.runtime.sampling.backends.base:SamplingBackend.speculative_sampling_pools"),
+)
+
+
+def sampled_hook_problems() -> list[str]:
+ """Recorded-proposal hooks required only when sampled trees are enabled."""
+ return [problem for hook in SAMPLED_HOOKS if (problem := _problem(hook))]
+
+
def contract() -> str | None:
"""``"capabilities"``, ``"release"``, or None when TokenSpeed has no plugin API."""
try:
diff --git a/eagle_harness/tokenspeed/measure_run.py b/eagle_harness/tokenspeed/measure_run.py
new file mode 100644
index 0000000..ca9c92f
--- /dev/null
+++ b/eagle_harness/tokenspeed/measure_run.py
@@ -0,0 +1,193 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Measure TokenSpeed draft and verify costs for a serve-mode profile.
+
+Run ``python -m eagle_harness.tokenspeed.measure_run --help`` for the driver.
+The engine uses the harness calibration policy through generic drafter hooks.
+Raw records, robust fits and the resulting profile belong to core.calibration.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+from collections import defaultdict
+from pathlib import Path
+
+from eagle_harness.core.calibration import (
+ AttentionShape,
+ CacheSweepPlan,
+ CalibrationPaths,
+ MeasureParams,
+ attention_shape,
+ fit_batch,
+ load_jsonl,
+ save_jsonl,
+)
+from eagle_harness.core.limits import ComputeIntensity, draft_query_lens, verify_buckets
+
+# Longer than the recorder's 512 rounds, including its first untimed verify.
+_MAX_NEW_TOKENS = 520
+_PROMPT = (
+ "Please explain how an operating system schedules threads, covering run queues, "
+ "priorities, time slices, preemption and load balancing across CPU cores. "
+) * 16
+
+
+def attention_config(config):
+ """Attention geometry and layer counts of a text or multimodal model."""
+ text = getattr(config, "text_config", None) or config
+ heads, kv_heads = text.num_attention_heads, text.num_key_value_heads
+ head_dim = getattr(text, "head_dim", None) or text.hidden_size // heads
+ ids = getattr(text, "full_attention_layer_ids", None)
+ # Hybrid configs that list their softmax layers by id may use other block names in layer_types.
+ shape = AttentionShape(len(ids)) if ids is not None else attention_shape(text)
+ if shape.attention_layers < 1:
+ raise ValueError("TokenSpeed calibration requires at least one softmax attention layer")
+ if shape.sliding_window_layers not in (0, shape.attention_layers):
+ # One attention geometry is measured per model: either every layer is windowed or none is.
+ raise ValueError("TokenSpeed calibration does not support mixed full and sliding-window attention layers")
+ window = shape.sliding_window if shape.sliding_window_layers else 0
+ shape = AttentionShape(shape.attention_layers, shape.sliding_window_layers, window)
+ return (heads, kv_heads, head_dim, window), shape
+
+
+def measure_batch(args, engine, input_ids, batch_size, target_cfg, draft_cfg, *, attention_samples=None):
+ """Run one fixed-size batch, then fit its stage and attention measurements.
+
+ The optional attention callable is the CPU fake-engine test boundary.
+ Missing stage samples fail before any fitted cost is written.
+ """
+ if attention_samples is None:
+ from eagle_harness.tokenspeed.attention_measurement import attention_samples
+
+ intensity = ComputeIntensity(args.compute_intensity)
+ paths = CalibrationPaths(args.run_dir)
+ params = MeasureParams(args.context_step, args.context_stop, batch_size,
+ args.num_draft_tokens, args.topk, args.num_draft_tokens,
+ 8 if args.fast else 16, args.fast)
+ CacheSweepPlan.from_params(params)
+ paths.write_measure_params(params)
+ # A failed or short retry must not reuse the preceding attempt's timings.
+ for model in ("slm", "llm"):
+ raw = Path(paths.raw(batch_size, "model", model))
+ if raw.exists():
+ for file in raw.glob("model_qo_len_*.jsonl"):
+ file.unlink()
+ engine.generate(input_ids=[input_ids] * batch_size,
+ sampling_params={"temperature": 0.0, "max_new_tokens": _MAX_NEW_TOKENS,
+ "ignore_eos": True})
+ drafts = [w for w in draft_query_lens(batch_size, intensity) if w <= args.topk]
+ verifies = sorted(w for w in verify_buckets(batch_size, intensity) if w <= args.num_draft_tokens)
+ for model, widths in (("slm", drafts), ("llm", verifies)):
+ for width in widths:
+ file = os.path.join(paths.raw(batch_size, "model", model), f"model_qo_len_{width}.jsonl")
+ records = load_jsonl(file)
+ if not records or any(r["batch_size"] != batch_size or r["time_intervals"] <= 0 for r in records):
+ raise RuntimeError(f"missing or invalid TokenSpeed measurements: {file}")
+
+ target_geometry, target_shape = attention_config(target_cfg)
+ draft_geometry, draft_shape = attention_config(draft_cfg)
+ for model, widths, rows, window, geometry in (
+ ("llm", verifies, args.num_draft_tokens, args.num_draft_tokens, target_geometry),
+ ("slm", drafts, args.topk, (args.num_steps - 1) * args.topk, draft_geometry),
+ ):
+ heads, kv_heads, head_dim, sliding = geometry
+ samples = attention_samples(
+ batch_size=batch_size, rows=rows, window=window,
+ num_q_heads=heads // args.tp_size, num_kv_heads=max(1, kv_heads // args.tp_size),
+ head_dim=head_dim, sliding_window=sliding, context_step=args.context_step,
+ context_stop=args.context_stop, fast=args.fast, repeat=params.repeat_cnt,
+ widths=widths, category=f"cache_{model}",
+ )
+ groups = defaultdict(list)
+ for sample in samples:
+ groups[sample.query_length].append(sample)
+ for width, records in groups.items():
+ save_jsonl(os.path.join(paths.raw(batch_size, "cache", model), f"cache_qo_len_{width}.jsonl"), records)
+ fit_batch(paths, params, intensity, draft_shape, target_shape, tp_size=args.tp_size)
+ stable = True
+ for model in ("slm", "llm"):
+ for kind, limit in (("cache", 0.20 if args.fast else 0.25), ("query", 0.30)):
+ for file in Path(paths.fitted(batch_size, kind, model)).glob("*.json"):
+ with file.open() as f:
+ stable &= json.load(f)["instability_rate"] < limit
+ return stable
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
+ parser.add_argument("--model", required=True)
+ parser.add_argument("--draft-model", required=True)
+ parser.add_argument("--run-dir", required=True)
+ parser.add_argument("--tp-size", type=int, required=True)
+ parser.add_argument("--compute-intensity", choices=[i.value for i in ComputeIntensity], required=True)
+ parser.add_argument("--topk", type=int, required=True)
+ parser.add_argument("--num-steps", type=int, required=True)
+ parser.add_argument("--num-draft-tokens", type=int, required=True)
+ parser.add_argument("--max-bs", type=int, required=True)
+ parser.add_argument("--mamba-ssm-dtype", choices=["float32", "bfloat16"], required=True)
+ parser.add_argument("--gpu-memory-utilization", type=float, default=0.85)
+ parser.add_argument("--context-step", type=int, default=64)
+ parser.add_argument("--context-stop", type=int, default=8192)
+ parser.add_argument("--fast", action="store_true")
+ args = parser.parse_args(argv)
+ chain = args.compute_intensity == "chain_intensity"
+ if not 1 <= args.max_bs <= (512 if chain else 32):
+ parser.error("--max-bs must be 1..512 for chains or 1..32 for trees")
+ if args.tp_size < 1 or args.topk not in ((1,) if chain else (2, 4, 8)):
+ parser.error("positive --tp-size and topk 1 (chain) or 2/4/8 (tree) required")
+ if not 2 <= args.num_steps <= (15 if chain else 32) or (args.num_steps - 1) * args.topk > 64:
+ parser.error("draft depth or lane window exceeds TokenSpeed limits")
+ if not 2 <= args.num_draft_tokens <= (16 if chain else 64):
+ parser.error("verify width exceeds TokenSpeed limits")
+ CacheSweepPlan.from_params(MeasureParams(args.context_step, args.context_stop, 1,
+ args.num_draft_tokens, args.topk, args.num_draft_tokens, 16))
+ run_dir = Path(args.run_dir)
+ if (run_dir / "cost").exists():
+ parser.error("--run-dir already contains costs, choose a fresh profile directory")
+
+ from tokenspeed.runtime.configs.model_config import get_hf_text_config
+ from tokenspeed.runtime.entrypoints.engine import Engine
+ from tokenspeed.runtime.utils.hf_transformers_utils import get_config
+ from transformers import AutoConfig, AutoTokenizer
+
+ target_cfg = get_hf_text_config(get_config(args.model, trust_remote_code=True))
+ draft_cfg = AutoConfig.from_pretrained(args.draft_model, trust_remote_code=True)
+ tokenizer = AutoTokenizer.from_pretrained(args.model)
+ input_ids = list(tokenizer(_PROMPT, add_special_tokens=False)["input_ids"])
+ run_dir.mkdir(parents=True, exist_ok=True)
+ # Initialize before startup can issue a warm-up prefill.
+ CalibrationPaths(args.run_dir).write_measure_params(MeasureParams(
+ args.context_step, args.context_stop, 1, args.num_draft_tokens, args.topk, args.num_draft_tokens, 16))
+ with (run_dir / "config" / "tokenspeed.json").open("w") as f:
+ json.dump(vars(args), f, indent=2)
+ engine = Engine(
+ model=args.model, attn_tp_size=args.tp_size, dtype="bfloat16",
+ max_model_len=max(4096, len(input_ids) + _MAX_NEW_TOKENS + 2 * args.num_draft_tokens),
+ max_num_seqs=args.max_bs, attention_backend="trtllm", sampling_backend="greedy",
+ disable_kvstore=True, speculative_algorithm="EAGLE_HARNESS",
+ speculative_draft_model_path=args.draft_model, speculative_eagle_topk=args.topk,
+ speculative_num_steps=args.num_steps, speculative_num_draft_tokens=args.num_draft_tokens,
+ speculative_algorithm_config=json.dumps({"mode": "calibrate", "data_path": args.run_dir,
+ "intensity": args.compute_intensity}),
+ mamba_ssm_dtype=args.mamba_ssm_dtype, gpu_memory_utilization=args.gpu_memory_utilization,
+ log_level="warning",
+ )
+ try:
+ for batch_size in range(1, args.max_bs + 1):
+ for attempt in range(4):
+ if measure_batch(args, engine, input_ids, batch_size, target_cfg, draft_cfg):
+ print(f"batch {batch_size}: calibrated", flush=True)
+ break
+ print(f"batch {batch_size}: unstable attempt {attempt + 1}/4", flush=True)
+ else:
+ raise RuntimeError(f"batch {batch_size} stayed unstable")
+ finally:
+ engine.shutdown()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/eagle_harness/tokenspeed/measurement.py b/eagle_harness/tokenspeed/measurement.py
new file mode 100644
index 0000000..761fb15
--- /dev/null
+++ b/eagle_harness/tokenspeed/measurement.py
@@ -0,0 +1,285 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""EAGLE-Harness cost measurement through generic TokenSpeed hooks.
+
+The measurement driver writes ``<run dir>/config/measure_config.json``
+(``{"batch_size": n}``) and sends ``n`` identical greedy requests.
+Every decode round then drafts the full depth at one draft width and
+verifies at one verify width, both cycled round-robin from a counter over the
+batch size's sweep (:func:`draft_widths`, :func:`verify_widths`;
+:class:`MeasurePolicy`), and commits exactly one fixed token per request,
+so the context grows by one token a round. Rank 0 times each round's draft
+depths (one draft step per sample, wall time between drained GPUs and a TP
+barrier) and the next forward's verify (target forward through the accept,
+events recorded inside the decode graph), and appends the samples
+:mod:`eagle_harness.core.calibration` processes.
+
+Only the rounds of a batch at the configured size count, and each prefill
+starts them afresh. Every rank counts them. The driver bounds request length and checks every
+width has samples before fitting.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+
+import torch
+import torch.distributed as dist
+
+from eagle_harness.core.calibration import CalibrationPaths, MeasureParams, MeasureRecord, save_model_timings
+from eagle_harness.core.limits import ComputeIntensity, draft_query_lens, verify_buckets
+from eagle_harness.tokenspeed.tree_round.device_policy import write_round_slots
+
+__all__ = [
+ "FORCED_TOKEN",
+ "MEASURED_ROUNDS",
+ "CostMeasurement",
+ "MeasurePolicy",
+ "draft_widths",
+ "verify_widths",
+]
+
+# The token every request commits each measured round.
+FORCED_TOKEN = 888
+# Verify (and draft) samples a batch records before it ends.
+MEASURED_ROUNDS = 512
+
+
+def draft_widths(batch_size: int, compute_intensity: str, node_top_k: int) -> list[int]:
+ return [w for w in draft_query_lens(batch_size, ComputeIntensity(compute_intensity)) if w <= node_top_k]
+
+
+def verify_widths(batch_size: int, compute_intensity: str) -> list[int]:
+ return verify_buckets(batch_size, ComputeIntensity(compute_intensity))
+
+
+class MeasurePolicy:
+ """Exec mode 2 decisions, taken on the host into device slots laid out as
+ :class:`DevicePolicy`'s: every depth at the round's draft width (the first at the
+ previous round's, as EAGLE-4 decides the first-step width before
+ the round's width), no early stop, every request verified at the round's
+ verify width. The device steps of a round have nothing to decide."""
+
+ def __init__(
+ self,
+ *,
+ verify_num: int,
+ node_top_k: int,
+ tree_depth: int,
+ compute_intensity: str,
+ device: torch.device,
+ ) -> None:
+ self.chain = compute_intensity == "chain_intensity"
+ self.chain_width_table = ()
+ self.eager_select_verify = False
+ self.verify_num_limit = verify_num
+ self.node_top_k = node_top_k
+ self.tree_depth = tree_depth
+ self.compute_intensity = compute_intensity
+ self.counter = 0
+ self.draft_width = node_top_k
+ self.previous_draft_width = node_top_k
+ self.verify_width_now = verify_num
+ # Per depth: width, pool start, work list size, go (DevicePolicy's layout).
+ self._slots = torch.zeros((4, tree_depth + 1), dtype=torch.int32, device=device)
+ self.widths, self.cumu_starts, self.work_sizes, _ = self._slots.unbind(0)
+ self._counts = torch.zeros((4,), dtype=torch.int32, device=device)
+ self.past_verify_num, self.cumu_count, self.verify_count, self.verify_num = (
+ self._counts.split(1)
+ )
+
+ def next_widths(self, batch_size: int, measured_batch_size: int) -> None:
+ """Advance the counter and pick the round's widths, verifying at most
+ the measured batch's widest verify width."""
+ self.counter += 1
+ ci = self.compute_intensity
+ drafts = draft_widths(batch_size, ci, self.node_top_k)
+ limit = min(max(verify_widths(measured_batch_size, ci)), self.verify_num_limit)
+ verifies = [w for w in verify_widths(batch_size, ci) if w <= limit]
+ self.previous_draft_width = self.draft_width
+ self.draft_width = drafts[self.counter % len(drafts)]
+ self.verify_width_now = verifies[self.counter % len(verifies)]
+
+ def write_round(self) -> None:
+ """The round's slots at the current widths."""
+ widths = [self.previous_draft_width]
+ widths += [self.draft_width] * (self.tree_depth - 2)
+ self._write(widths, self.verify_width_now)
+
+ def write_full_round(self) -> None:
+ """Slots of a round drafting every depth at full width."""
+ widths = [self.node_top_k] * (self.tree_depth - 1)
+ self._write(widths, self.verify_num_limit)
+
+ def _write(self, widths: list[int], verify_num: int) -> None:
+ start = write_round_slots(self._slots, self.node_top_k, widths, lambda d, s: 0)
+ verify_count = min(self.verify_num_limit, start)
+ # The tree holds only the ranked nodes; the verify forward runs every row anyway.
+ verify_num = min(verify_num, verify_count)
+ self._counts.copy_(
+ torch.tensor(
+ [self.verify_num_limit, start, verify_count, verify_num],
+ dtype=torch.int32,
+ )
+ )
+
+ def go_ready(self, depth: int, seq: int = 0) -> bool:
+ return depth < self.tree_depth
+
+ def table_width(self, batch_size: int) -> int:
+ return 0
+
+ def observe_batch_size(self, batch_size: int) -> None:
+ pass
+
+ def deltas_depth(self, depth: int) -> bool:
+ return False
+
+ def begin_round(
+ self, live_rows: torch.Tensor, frontier: torch.Tensor, sampled: torch.Tensor
+ ) -> None:
+ """The round's slots are written before it."""
+
+ def decide(self, depth: int, work_deltas: torch.Tensor) -> None:
+ """Measured widths are decided before the round."""
+
+ def select_verify(self, top_scores: torch.Tensor) -> None:
+ """Measured rounds verify at the width written before the round."""
+
+
+class CostMeasurement:
+ """Round timers and samples. Only rank zero writes the shared profile.
+
+ The synchronous driver keeps the measurement config immutable while
+ requests run, so each TP rank reads the same batch size on prefill.
+ """
+
+ def __init__(
+ self,
+ *,
+ run_dir: str,
+ tree_depth: int,
+ tp_group,
+ rank: int,
+ device: torch.device,
+ ) -> None:
+ self.run_dir = run_dir
+ self.config_path = os.path.join(run_dir, "config", "measure_config.json")
+ self.tree_depth = tree_depth
+ self.tp_group = tp_group
+ self._barrier = torch.zeros((1,), dtype=torch.int32, device=device)
+ self.recorder = rank == 0
+ # The batch size the driver measures (None before it wrote one).
+ self.measured_batch_size: int | None = None
+ self.params: MeasureParams | None = None
+ self.records: list[MeasureRecord] = []
+ # Committed token of every request, read in-graph: FORCED_TOKEN throughout the fixed-length request.
+ self.commit_token = torch.full(
+ (1,), FORCED_TOKEN, dtype=torch.int32, device=device
+ )
+ # Recorded inside the decode graph around the target forward and verify.
+ self.verify_start = torch.cuda.Event(enable_timing=True, external=True)
+ self.verify_end = torch.cuda.Event(enable_timing=True, external=True)
+ self.draft_start = torch.cuda.Event(enable_timing=True)
+ self.draft_end = torch.cuda.Event(enable_timing=True)
+ # (verify width, context) of the tree the next forward verifies.
+ self.pending_verify: tuple[int, int] | None = None
+ # Rounds of the batch counted on every rank (rank 0 also keeps their samples).
+ self.verify_rounds = 0
+ self.draft_rounds = 0
+ self.written = False
+
+ def on_extend(self) -> None:
+ """A prefill: reload the measured batch size and start the batch afresh."""
+ path = self.config_path
+ # The synchronous driver writes before generate and never mutates the file in flight.
+ self.measured_batch_size = None
+ if os.path.exists(path):
+ with open(path, encoding="utf-8") as f:
+ self.params = MeasureParams(**json.load(f))
+ self.measured_batch_size = self.params.batch_size
+ self.records = []
+ self.pending_verify = None
+ self.verify_rounds = 0
+ self.draft_rounds = 0
+ self.written = False
+ self.commit_token.fill_(FORCED_TOKEN)
+
+ @property
+ def finished(self) -> bool:
+ """Whether the batch has its rounds (the same on every rank)."""
+ return self.verify_rounds >= MEASURED_ROUNDS
+
+ def recording(self, batch_size: int) -> bool:
+ return batch_size == self.measured_batch_size and not self.finished
+
+ def _drain(self) -> None:
+ if self.tp_group is not None:
+ # Device group: the control plane's CPU collectives run on the event-loop thread.
+ dist.all_reduce(self._barrier, group=self.tp_group)
+ torch.cuda.synchronize()
+
+ def record_verify(self, batch_size: int) -> None:
+ """The verify this forward ran, if it verified a measured round."""
+ pending, self.pending_verify = self.pending_verify, None
+ if pending is None or not self.recording(batch_size):
+ return
+ self.verify_rounds += 1
+ if self.recorder:
+ self.verify_end.synchronize()
+ elapsed = int(self.verify_start.elapsed_time(self.verify_end) * 1000)
+ self._append(elapsed, 1, pending[0], pending[1], "model_llm", batch_size)
+
+ def begin_draft(self) -> None:
+ self._drain()
+ self.draft_start.record()
+
+ def end_draft(
+ self, batch_size: int, draft_width: int, verify_width: int, cache_len: int
+ ) -> None:
+ self._drain()
+ self.draft_end.record()
+ if not self.recording(batch_size) or self.draft_rounds >= MEASURED_ROUNDS:
+ return
+ self.draft_rounds += 1
+ self.pending_verify = (verify_width, cache_len)
+ if self.recorder:
+ self.draft_end.synchronize()
+ elapsed = int(self.draft_start.elapsed_time(self.draft_end) * 1000)
+ self._append(
+ elapsed,
+ self.tree_depth - 1,
+ draft_width,
+ cache_len,
+ "model_slm",
+ batch_size,
+ )
+
+ def _append(
+ self,
+ elapsed: int,
+ count: int,
+ width: int,
+ cache_len: int,
+ category: str,
+ batch_size: int,
+ ) -> None:
+ if elapsed <= 0:
+ raise RuntimeError(f"{category} sample of {elapsed} us")
+ self.records.append(
+ MeasureRecord(elapsed, count, width, cache_len, category, batch_size)
+ )
+
+ def complete(self) -> bool:
+ """Whether rank 0 holds the finished batch's samples, not written yet."""
+ return self.recorder and self.finished and not self.written
+
+ def write_model_records(self) -> str:
+ """Write the batch's raw stage samples under ``test/bs_<n>``; returns that directory."""
+ test_dir = os.path.join(self.run_dir, "test", f"bs_{self.measured_batch_size}")
+ assert self.params is not None
+ save_model_timings(CalibrationPaths(self.run_dir), self.params, self.records)
+ self.written = True
+ return test_dir
diff --git a/eagle_harness/tokenspeed/models.py b/eagle_harness/tokenspeed/models.py
index 8c758f2..7f3467d 100644
--- a/eagle_harness/tokenspeed/models.py
+++ b/eagle_harness/tokenspeed/models.py
@@ -44,6 +44,7 @@ class CandidateRows(LogitsProcessorOutput):
"""
normed: torch.Tensor | None = None
+ candidate_ids: torch.Tensor | None = None
class LlamaForCausalLMEagle4(LlamaForCausalLMEagle3):
diff --git a/eagle_harness/tokenspeed/tree_rejection.py b/eagle_harness/tokenspeed/tree_rejection.py
new file mode 100644
index 0000000..ca363a0
--- /dev/null
+++ b/eagle_harness/tokenspeed/tree_rejection.py
@@ -0,0 +1,116 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Draft-tree verification by recursive rejection sampling."""
+
+from __future__ import annotations
+
+import torch
+from tokenspeed_kernel.ops.sampling import argmax as sampling_argmax
+from tokenspeed_kernel.ops.sampling.cuda import (
+ fused_topk_topp_available as _FUSED_TOPK_TOPP_AVAILABLE,
+)
+from tokenspeed_kernel.ops.sampling.cuda import (
+ fused_topk_topp_renorm,
+)
+from tokenspeed_kernel.ops.sampling.flashinfer import (
+ softmax,
+ top_k_renorm_prob,
+ top_p_renorm_prob,
+)
+from tokenspeed_kernel.ops.sampling.triton import gather_and_expand_scalars
+from eagle_harness.tokenspeed.tree_round.ops.rejection import (
+ residual_sample,
+ tree_reject_sample,
+)
+
+from tokenspeed.runtime.sampling.backends.base import SpeculativeSamplingPools
+from tokenspeed.runtime.sampling.tree_verify import DraftTreeQ, TreeVerifyBatch
+
+__all__ = ["TreeRejectionSampler"]
+
+
+class TreeRejectionSampler:
+ """Accepts each request's draft tree by rejection sampling against the
+ target p' (the softmax at the request's temperature, cut to its top-k and
+ top-p and renormalized; a row that cuts nothing keeps its softmax values).
+ Children drawn from the draft q (``tree.draft_q``) are accepted by
+ recursive rejection without replacement, the others by their p' over the
+ mass left; the bonus token comes from the last accepted node's residual.
+ Exact for any draft.
+
+ A greedy row (top-k 1) has a one-hot p' at the logits' lowest-index argmax
+ (``sampling_argmax``): its first child holding the argmax is accepted and
+ its bonus is the argmax, so it skips the residual scan and, with the fused
+ top-k / top-p kernel, the softmax and the cut.
+ """
+
+ def __init__(self, pools: SpeculativeSamplingPools, max_bs: int, device: torch.device | str) -> None:
+ # The verifier's per-request sampling scalars, indexed by pool slot.
+ self.pools = pools
+ # Each request's last accepted node's row of the target probs.
+ self.last_row = torch.zeros((max_bs,), dtype=torch.int64, device=device)
+ # Stands in for the draft q of trees without sampled nodes (never read).
+ self.no_draft_q = DraftTreeQ.zeros(1, 1, 1, 1, device)
+
+ def __call__(
+ self,
+ logits: torch.Tensor,
+ candidates: torch.Tensor,
+ tree: TreeVerifyBatch,
+ req_pool_indices: torch.Tensor,
+ *,
+ coins: torch.Tensor,
+ final_coins: torch.Tensor,
+ path: torch.Tensor,
+ predict: torch.Tensor,
+ accept_length: torch.Tensor,
+ ) -> None:
+ """Verify ``candidates`` (``[bs, N]`` tree tokens) against ``logits``
+ (``[bs * N, V]``) with one uniform per child in ``coins`` (``[bs, N]``)
+ and per bonus in ``final_coins`` (``[bs]``); writes ``path``
+ (``[bs, N]``), ``predict`` (``[bs * N]``) and ``accept_length``
+ (``[bs]``) as ``SamplingBackend.verify`` returns them."""
+ bs, n = candidates.shape
+ last_row = self.last_row[:bs]
+ temperatures, top_ks, top_ps, _, _, _ = gather_and_expand_scalars(
+ req_pool_indices,
+ temperature=self.pools.temperature,
+ top_k=self.pools.top_k,
+ top_p=self.pools.top_p,
+ n=n,
+ )
+ # The unfused cut reads every row, so only the fused one lets greedy rows skip.
+ probs = softmax(
+ logits,
+ temperature=temperatures,
+ skip_greedy_top_ks=top_ks if _FUSED_TOPK_TOPP_AVAILABLE else None,
+ )
+ if _FUSED_TOPK_TOPP_AVAILABLE:
+ probs = fused_topk_topp_renorm(probs, top_ks, top_ps, in_place_skip=True)
+ else:
+ cut = top_k_renorm_prob(probs, top_ks)
+ cut = top_p_renorm_prob(cut, top_ps, is_deterministic=True)
+ uncut = (top_ks >= probs.shape[1]) & (top_ps >= 1.0)
+ probs = torch.where(uncut[:, None], probs, cut)
+ argmax = sampling_argmax(logits)
+ draft_q = tree.draft_q
+ q = draft_q if draft_q is not None else self.no_draft_q
+ tree_reject_sample(
+ probs,
+ candidates.to(torch.int32),
+ tree.parents,
+ req_pool_indices if draft_q is not None else None,
+ q.slot,
+ q.pos,
+ q.q,
+ q.q_ids,
+ coins,
+ top_ks,
+ argmax,
+ path,
+ predict,
+ accept_length,
+ last_row,
+ )
+ residual_sample(probs, last_row, final_coins, top_ks, argmax, accept_length, predict, n)
diff --git a/eagle_harness/tokenspeed/tree_round/__init__.py b/eagle_harness/tokenspeed/tree_round/__init__.py
new file mode 100644
index 0000000..6ff9f6c
--- /dev/null
+++ b/eagle_harness/tokenspeed/tree_round/__init__.py
@@ -0,0 +1,4 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Deferred tree rounds; import runtime classes from their owning modules."""
diff --git a/eagle_harness/tokenspeed/tree_round/chain.py b/eagle_harness/tokenspeed/tree_round/chain.py
new file mode 100644
index 0000000..8593edd
--- /dev/null
+++ b/eagle_harness/tokenspeed/tree_round/chain.py
@@ -0,0 +1,128 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""EAGLE-Harness device-chained rounds: a round's captured graphs launch one
+another on the GPU, so the host launches depth 1 and never waits on the
+round's decisions.
+
+Each depth's graph holds a kernel, right after the depth's decision, that
+tail-launches the round's next graph of its padded batch: depth ``d + 1``
+while ``go[d + 1]`` is set, else the greedy or sampled finalize graph. A tail
+launch starts once the launching graph has completed, and the stream that
+launched depth 1 runs its later work after the whole round. Depth 1 is an
+ordinary graph the host launches; the later depths and the finalize are
+instantiated for device launch, which allows kernel, memcpy and memset nodes
+and fork/join edges, but no event nodes. A device launch skips torch's
+``CUDAGraph.replay``; these round graphs must capture no torch random
+op. A missing graph handle traps on the device. ``instantiate`` requires
+a contiguous depth prefix and one greedy, optionally one sampled, finalizer.
+"""
+
+from __future__ import annotations
+
+import torch
+
+from eagle_harness.tokenspeed.tree_round.ops.chain import (
+ eagle_harness_chain_destroy,
+ eagle_harness_chain_instantiate,
+ eagle_harness_chain_load,
+ eagle_harness_chain_next,
+)
+
+__all__ = ["DeviceChain"]
+
+
+class DeviceChain:
+ """The device-launchable round graphs of each padded batch.
+
+ Args:
+ max_bs: The largest padded batch.
+ last_depth: The deepest depth a round drafts (``tree_depth - 1``).
+ device: The CUDA device the rounds run on.
+ """
+
+ def __init__(self, max_bs: int, last_depth: int, device: torch.device) -> None:
+ if not 1 <= max_bs <= 512 or not 1 <= last_depth <= 31:
+ raise ValueError(
+ "DeviceChain needs max_bs in 1..512 and last_depth in 1..31"
+ )
+ self.device = torch.device(device)
+ if self.device.type != "cuda":
+ raise ValueError("DeviceChain requires a CUDA device")
+ self.last_depth = last_depth
+ # Per padded batch: depth d's exec at column d (from 2), then the
+ # greedy and sampled finalizers at fixed columns; uncaptured slots stay zero.
+ self._execs = torch.zeros(
+ (max_bs + 1, last_depth + 3), dtype=torch.int64, device=device
+ )
+ # Per padded batch: the exec handles it owns.
+ self._handles: dict[int, list[int]] = {}
+ # Loaded here: the first launch may be inside a graph capture.
+ with torch.cuda.device(self.device):
+ eagle_harness_chain_load()
+
+ def end_depth(
+ self, rows: int, depth: int, go: torch.Tensor, sampled: torch.Tensor
+ ) -> None:
+ """Enqueue, inside depth ``depth``'s graph at padded batch ``rows``,
+ the launch of the round's next graph, which starts once that graph
+ has ended. ``sampled`` selects the captured finalizer."""
+ if not 1 <= rows < self._execs.shape[0] or not 1 <= depth <= self.last_depth:
+ raise ValueError("DeviceChain rows/depth outside the captured shape")
+ eagle_harness_chain_next(self._execs[rows], go, sampled, depth, self.last_depth)
+
+ def instantiate(
+ self,
+ rows: int,
+ depths: list[torch.cuda.CUDAGraph],
+ finalize: list[torch.cuda.CUDAGraph],
+ stream: torch.cuda.Stream,
+ ) -> None:
+ """Instantiate the graphs of padded batch ``rows`` (``keep_graph``
+ captures) for device launch: ``depths`` is a prefix starting at depth 2;
+ ``finalize`` is greedy, then optionally sampled. Publish on the upload stream; callers
+ must order that stream before replay. Call release before recapturing."""
+ if not 1 <= rows < self._execs.shape[0]:
+ raise ValueError("DeviceChain rows outside the captured shape")
+ if rows in self._handles:
+ raise ValueError(
+ f"DeviceChain batch {rows} already instantiated; release before replacing"
+ )
+ if len(depths) > self.last_depth - 1 or len(finalize) not in (1, 2):
+ raise ValueError(
+ "DeviceChain requires a depth prefix from 2 and one or two finalizers"
+ )
+ if stream.device != self._execs.device:
+ raise ValueError("DeviceChain upload stream must be on the graph device")
+ handles = []
+ with torch.cuda.device(self.device), torch.cuda.stream(stream):
+ try:
+ for graph in (*depths, *finalize):
+ handles.append(
+ eagle_harness_chain_instantiate(
+ graph.raw_cuda_graph(), stream.cuda_stream
+ )
+ )
+ row = [0] * (self.last_depth + 3)
+ row[2 : 2 + len(depths)] = handles[: len(depths)]
+ finalize_col = self.last_depth + 1
+ row[finalize_col : finalize_col + len(finalize)] = handles[
+ len(depths) :
+ ]
+ self._execs[rows].copy_(torch.tensor(row, dtype=torch.int64))
+ except Exception:
+ stream.synchronize()
+ for handle in handles:
+ eagle_harness_chain_destroy(handle)
+ raise
+ self._handles[rows] = handles
+
+ def release(self) -> None:
+ """Free every exec handle, once no round runs."""
+ with torch.cuda.device(self.device):
+ torch.cuda.synchronize(self.device)
+ for handles in self._handles.values():
+ for handle in handles:
+ eagle_harness_chain_destroy(handle)
+ self._handles.clear()
+ self._execs.zero_()
diff --git a/eagle_harness/tokenspeed/tree_round/device_policy.py b/eagle_harness/tokenspeed/tree_round/device_policy.py
new file mode 100644
index 0000000..7ca8f28
--- /dev/null
+++ b/eagle_harness/tokenspeed/tree_round/device_policy.py
@@ -0,0 +1,367 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Graph-capturable round decisions; costs are supplied by the shared core model."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from typing import cast
+
+import torch
+
+from eagle_harness.tokenspeed.tree_round.ops.build import load_module
+from eagle_harness.tokenspeed.tree_round.ops.policy import (
+ eagle_harness_policy_begin_round,
+ eagle_harness_policy_decide_chain,
+ eagle_harness_policy_decide_tree,
+ eagle_harness_policy_load,
+ eagle_harness_policy_select_verify,
+)
+from eagle_harness.tokenspeed.tree_round.policy_cost import (
+ ChainPolicyCosts,
+ TreePolicyCosts,
+ build_chain_tables,
+ build_tables,
+)
+
+__all__ = ["DevicePolicy", "write_round_slots"]
+
+# Scalars of the int32 state tensor (``State`` in eagle_harness_policy.cu).
+(
+ _TINY,
+ _TIER,
+ _SAMPLED_NEXT,
+ _SAMPLED_PLAN,
+ _SAMPLED_SEEN,
+ _BENCH_BATCH_SIZE,
+ _RANKED_COUNT,
+ _BATCH_SIZE,
+ _SAMPLED,
+ _COST_ID,
+ _INTERVAL,
+ _VARIANT,
+ _HIST_MAX,
+ _PAST_VERIFY_NUM,
+ _LAST_DEPTH,
+ _STOP_WIDTH,
+ _CUMU_COUNT,
+ _VERIFY_COUNT,
+ _FLAT,
+ _VERIFY_NUM,
+ _TABLE_WIDTH,
+ _NUM_STATE,
+) = range(22)
+# Rows of the slot tensor (``SlotRow``).
+_WIDTH_ROW, _CUMU_START_ROW, _WORK_SIZE_ROW, _GO_ROW, _NUM_SLOT_ROWS = range(5)
+
+
+def write_round_slots(
+ slots: torch.Tensor,
+ node_top_k: int,
+ widths: list[int],
+ work_size: Callable[[int, int], int],
+) -> int:
+ """Write the ``[4, tree_depth + 1]`` device ``slots`` of a round drafting
+ depth ``d >= 1`` at ``widths[d - 1]`` with ``work_size(d, cumu_start)``
+ work deltas; returns its pool size."""
+ host = torch.zeros(slots.shape, dtype=torch.int32)
+ start = 1 + node_top_k
+ for depth, width in enumerate(widths, start=1):
+ host[:, depth] = torch.tensor([width, start, work_size(depth, start), 1])
+ start += node_top_k * width
+ slots.copy_(host)
+ return start
+
+
+class DevicePolicy:
+ """Device-only serving policy with a fixed verify window.
+
+ ``costs`` supplies host-only structural records computed by the caller.
+ The engine packs these records without constructing a cost model. Trees
+ support K=2/4/8, 2..32 depths, <=64 lane slots, N=2..64 and 32 requests.
+ Chains support K=1, 2..15 depths, N=2..16 and 512 requests. Only serving
+ (exec_mode=0) is supported. A chain width table supplies increasing
+ ``(min_batch_size, width)`` pairs; uncovered batches use the cost rule.
+ ``verify_num`` on the device is the meaningful node count, not the fixed
+ window size: write_verify_tree pads the rest with roots (parent -1).
+
+ Call observe_batch_size, begin_round, then decide before each draft
+ depth, then select_verify on the ranked pool scores. Counts stay on the
+ device; go_ready optionally polls a pinned mirror. Sampled rounds fix
+ depth before drawing proposals, observing costs only for the next plan.
+ Construct under the desired CUDA device before any graph capture.
+ """
+
+ def __init__(
+ self,
+ costs: TreePolicyCosts | ChainPolicyCosts | None,
+ *,
+ verify_num: int,
+ node_top_k: int,
+ tree_depth: int,
+ compute_intensity: str,
+ is_moe_target: bool,
+ exec_mode: int,
+ benchmark_config: str = "",
+ chain_width_table: tuple[tuple[int, int], ...] = (),
+ device: torch.device,
+ ) -> None:
+ if compute_intensity not in (
+ "high_intensity",
+ "low_intensity",
+ "chain_intensity",
+ ):
+ raise ValueError("DevicePolicy needs high, low or chain intensity")
+ if exec_mode != 0 or benchmark_config:
+ raise ValueError(
+ "DevicePolicy supports serving only (exec_mode=0, no benchmark config)"
+ )
+ self.chain = compute_intensity == "chain_intensity"
+ self.chain_width_table = chain_width_table
+ if self.chain:
+ if (
+ any(type(v) is not int for v in (node_top_k, tree_depth, verify_num))
+ or node_top_k != 1
+ or not 2 <= tree_depth <= 15
+ or not 2 <= verify_num <= 16
+ ):
+ raise ValueError(
+ "DevicePolicy chain needs K=1, depth 2..15 and verify 2..16"
+ )
+ else:
+ if chain_width_table:
+ raise ValueError("DevicePolicy trees run no chain width table")
+ if node_top_k not in (2, 4, 8) or not 2 <= tree_depth <= 32:
+ raise ValueError("DevicePolicy needs K=2/4/8 and tree_depth in 2..32")
+ if (tree_depth - 1) * node_top_k > 64:
+ raise ValueError("DevicePolicy lane window exceeds 64 slots")
+ if not 2 <= verify_num <= 64:
+ raise ValueError("DevicePolicy verify_num must be in 2..64")
+ self.device = torch.device(device)
+ if self.device.type != "cuda":
+ raise ValueError("DevicePolicy requires a CUDA device")
+ self.chain_past_verify_num = 16 if self.chain else 0
+ self.node_top_k = node_top_k
+ self.tree_depth = tree_depth
+ self.verify_num_limit = verify_num
+ self.high_intensity = compute_intensity == "high_intensity"
+ self.is_moe_target = is_moe_target
+ self.exec_mode = exec_mode
+ self.eager_select_verify = False
+ max_bs = 512 if self.chain else 32
+ self.async_layer_ratio: float | None = None
+ if self.chain:
+ self._tables = build_chain_tables(
+ cast(ChainPolicyCosts, costs),
+ tree_depth=tree_depth,
+ verify_num=verify_num,
+ chain_width_table=chain_width_table,
+ device=self.device,
+ )
+ else:
+ tree_costs = cast(TreePolicyCosts, costs)
+ self._tables = build_tables(tree_costs, device=self.device)
+ packed_depth = (
+ self._tables.interval_f64.shape[-1]
+ - 2
+ - (self._tables.interval_i32.shape[-1] - 1) ** 2
+ ) // 5
+ if packed_depth != tree_depth:
+ raise ValueError("cost records must match the policy tree_depth")
+ if any(width > node_top_k for width in tree_costs.initial_widths):
+ raise ValueError("cost records exceed the policy node_top_k")
+ self.async_layer_ratio = tree_costs.async_layer_ratio
+ # Resolve libraries before capture on the device that will run them.
+ with torch.cuda.device(self.device):
+ eagle_harness_policy_load()
+ load_module("tree")
+ state = [0] * _NUM_STATE
+ state[_SAMPLED_SEEN] = -1
+ # The reference starts sampled chains at the root, trees at full depth.
+ state[_SAMPLED_NEXT] = 0 if self.chain else tree_depth - 1
+ hist = (
+ torch.zeros((max_bs, 0), dtype=torch.int32)
+ if self.chain
+ else torch.full((max_bs, 16), verify_num, dtype=torch.int32)
+ )
+ recent = (
+ torch.zeros(0, dtype=torch.int32)
+ if self.chain
+ else torch.arange(-5, 0, dtype=torch.int32)
+ )
+ self._state = torch.tensor(state, dtype=torch.int32, device=device)
+ self._hist = hist.to(device=device, dtype=torch.int32)
+ self._recent = recent.to(device=device, dtype=torch.int32)
+ # The ranked scores the next round sizes its verify on (none before the first).
+ self._ranked = torch.zeros(
+ (max_bs * verify_num,), dtype=torch.float32, device=device
+ )
+ self._slots = torch.zeros(
+ (_NUM_SLOT_ROWS, self.tree_depth + 1), dtype=torch.int32, device=device
+ )
+ # The round's cost row, copied by begin_round for its decisions.
+ depth = self.tree_depth
+ self._round_f64 = torch.zeros(
+ (5 * depth if self.chain else 2 + depth,),
+ dtype=torch.float64,
+ device=device,
+ )
+ self._round_seq = torch.zeros((1,), dtype=torch.int64, device=device)
+ self.go_host = torch.zeros(
+ (self.tree_depth + 1,), dtype=torch.int64, pin_memory=True
+ )
+ self._go_host_view = self.go_host.numpy()
+
+ self.past_verify_num = self._state[_PAST_VERIFY_NUM : _PAST_VERIFY_NUM + 1]
+ self.widths = self._slots[_WIDTH_ROW]
+ self.cumu_starts = self._slots[_CUMU_START_ROW]
+ self.work_sizes = self._slots[_WORK_SIZE_ROW]
+ self.go = self._slots[_GO_ROW]
+ self.cumu_count = self._state[_CUMU_COUNT : _CUMU_COUNT + 1]
+ self.verify_count = self._state[_VERIFY_COUNT : _VERIFY_COUNT + 1]
+ self.flat = self._state[_FLAT : _FLAT + 1]
+ self.verify_num = self._state[_VERIFY_NUM : _VERIFY_NUM + 1]
+ # The depth whose decision stopped the round, and that decision's width.
+ self.last_depth = self._state[_LAST_DEPTH : _LAST_DEPTH + 1]
+ self.stop_width = self._state[_STOP_WIDTH : _STOP_WIDTH + 1]
+
+ def table_width(self, batch_size: int) -> int:
+ """Explicit scheduled width, or zero when this batch uses measured costs."""
+ width = 0
+ for minimum, candidate in self.chain_width_table:
+ if batch_size < minimum:
+ break
+ width = candidate
+ return width
+
+ def observe_batch_size(self, batch_size: int) -> None:
+ """Validate the live batch on the host before entering a round."""
+ max_bs = 512 if self.chain else 32
+ if not 0 <= batch_size <= max_bs:
+ raise ValueError(
+ f"DevicePolicy needs 0..{max_bs} live requests, got {batch_size}"
+ )
+
+ def begin_round(
+ self, live_rows: torch.Tensor, frontier: torch.Tensor, sampled: torch.Tensor
+ ) -> None:
+ """Start a round; sampled is a device bool [1] selecting sampled proposals.
+
+ live_rows is int32 [1] (0..32 tree, 0..512 chain); frontier is int64 lengths.
+ Counts and decisions stay on the device, including during graph capture.
+ """
+ t = self._tables
+ eagle_harness_policy_begin_round(
+ self._state,
+ self._round_seq,
+ self._hist,
+ self._slots,
+ self.go_host,
+ t.batch_table,
+ t.tier_table,
+ t.chain_f64 if self.chain else t.interval_f64,
+ self._round_f64,
+ live_rows,
+ frontier,
+ sampled,
+ self.chain,
+ self.node_top_k,
+ self.chain_past_verify_num,
+ self.verify_num_limit,
+ 16,
+ )
+
+ def deltas_depth(self, depth: int) -> bool:
+ """Whether this non-final depth requests deltas: tree even, chain odd."""
+ return depth < self.tree_depth - 1 and depth % 2 == int(self.chain)
+
+ def write_full_round(self) -> None:
+ """Slots of a round drafting every depth at full width, which the
+ drafter warms its depths up on outside a round (rounds rewrite them).
+ No round is live afterwards: decisions launched on these slots (a
+ warm-up) write nothing."""
+ width = 1 if self.chain else self.node_top_k
+ past = self.chain_past_verify_num if self.chain else self.verify_num_limit
+ write_round_slots(
+ self._slots,
+ self.node_top_k,
+ [width] * (self.tree_depth - 1),
+ lambda depth, start: min(past, start) if self.deltas_depth(depth) else 0,
+ )
+ self.past_verify_num.fill_(past)
+ self._state[_BATCH_SIZE].fill_(0)
+
+ def decide(self, depth: int, work_deltas: torch.Tensor) -> None:
+ """Decide before depth d drafts, using depth d-1 work deltas (fp32 [K+1]).
+
+ Writes the next depth slots or stops with cumu_count, verify_count and flat.
+ """
+ if self.chain:
+ eagle_harness_policy_decide_chain(
+ self._state,
+ self._round_seq,
+ self._slots,
+ self.go_host,
+ work_deltas,
+ self._round_f64,
+ depth,
+ self.verify_num_limit,
+ )
+ return
+ assert self.async_layer_ratio is not None
+ eagle_harness_policy_decide_tree(
+ self._state,
+ self._round_seq,
+ self._slots,
+ self.go_host,
+ work_deltas,
+ self._round_f64,
+ self._tables.tier_table,
+ depth,
+ self.node_top_k,
+ self.exec_mode,
+ self.async_layer_ratio,
+ self.verify_num_limit,
+ 16,
+ )
+
+ def select_verify(self, top_scores: torch.Tensor) -> None:
+ """Publish cumulative ranked scores and choose the meaningful verify count.
+
+ top_scores is fp32 [rows >= live rows, cols >= verify_count], in rank
+ order. The previous round's scores choose this round's count (its own
+ scores on the first greedy round; no scores on the first sampled round),
+ recorded in the verify history. Chains verify their whole pool and
+ update the next sampled plan when their stopping decision runs. Reductions
+ follow torch's default CUDA cumsum; deterministic algorithms are refused.
+ """
+ if self.chain:
+ return
+ if torch.are_deterministic_algorithms_enabled():
+ raise RuntimeError(
+ "the device ranked scores replicate torch's default cumsum, not its deterministic one"
+ )
+ t = self._tables
+ eagle_harness_policy_select_verify(
+ self._state,
+ self._recent,
+ self._hist,
+ self._ranked,
+ top_scores,
+ t.interval_i32,
+ t.interval_f64,
+ t.verify_i32,
+ t.verify_f64,
+ self.tree_depth,
+ self.exec_mode,
+ )
+
+ def go_ready(self, depth: int, round_seq: int) -> bool | None:
+ """Whether depth ``depth`` drafts in round ``round_seq`` (the
+ ``begin_round`` count, from 1), from the pinned mirror without a
+ synchronization: None until the decision wrote it."""
+ value = int(self._go_host_view[depth])
+ if value >> 1 != round_seq:
+ return None
+ return bool(value & 1)
diff --git a/eagle_harness/tokenspeed/tree_round/dynamic.py b/eagle_harness/tokenspeed/tree_round/dynamic.py
new file mode 100644
index 0000000..5a0d202
--- /dev/null
+++ b/eagle_harness/tokenspeed/tree_round/dynamic.py
@@ -0,0 +1,950 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Device-decided tree rounds on TokenSpeed's draft lanes.
+
+The decode graph owns target verification and draft extend. Each following
+frontier has its own graph; the GPU tail-launches the next depth or finalize.
+The host joins the pending round before any next-forward state mutation.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from tokenspeed.runtime.sampling.tree_verify import DraftTreeQ
+
+import torch
+from tokenspeed.runtime.execution.context import ForwardContext
+from tokenspeed.runtime.execution.drafter.eagle import (
+ AcceptedPrefixPublisher,
+ Eagle,
+ EagleDraftInput,
+)
+from tokenspeed.runtime.execution.forward_batch_info import (
+ CaptureHiddenMode,
+ ForwardMode,
+)
+from tokenspeed.runtime.execution.output_layout import ForwardOutputLayout
+from tokenspeed.runtime.layers.logits_processor import LogitsProcessorOutput
+from tokenspeed.runtime.sampling.backends.base import (
+ SamplingBackend,
+ SpeculativeSamplingPools,
+)
+from tokenspeed.runtime.sampling.sampling_params import SamplingParams
+from tokenspeed.runtime.utils.common import maybe_inference_mode
+from typing_extensions import override
+
+from eagle_harness.tokenspeed.tree_round.chain import DeviceChain
+from eagle_harness.tokenspeed.tree_round.device_policy import DevicePolicy
+from eagle_harness.tokenspeed.tree_round.ops.tree import (
+ eagle_harness_draft_depth_update,
+ eagle_harness_publish_draft_q,
+ eagle_harness_sample_children,
+ eagle_harness_stable_topk_desc,
+ eagle_harness_update_node_data,
+ eagle_harness_work_deltas,
+ eagle_harness_write_verify_tree,
+)
+
+_ROOT_SCORE = 1.001
+
+
+class _PendingRound:
+ ctx: ForwardContext
+ stream: torch.cuda.Stream
+ bs: int
+ rows: int
+ graphs: bool
+ seq: int
+ sampled: bool = False
+ chained: bool = False
+ depth: int = 1
+
+
+class DynamicDrafter(Eagle):
+ """Deferred device-policy rounds; static mode retains Eagle's whole graph."""
+
+ supports_speculative_sampling = True
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.policy = None
+ self._pool = {}
+ self._round = {}
+ self._pending = None
+ self._chain = None
+ self._launched_rows = None
+ self._round_seq = 0
+ self._depth_graphs = {}
+ self._finalize_graphs = {}
+ self._live_rows = 0
+ self._live_sampled = False
+ self._root_children = None
+ self._depth_done = []
+ self._decide_stream = None
+ self._round_stream = None
+ self._target_done = None
+ self._round_done = None
+ self._sampling_backend: SamplingBackend | None = None
+ self._pools: SpeculativeSamplingPools | None = None
+ self._sampled: dict[str, torch.Tensor] = {}
+ self._sampled_q: DraftTreeQ | None = None
+ self._sampled_seed: int = 0
+ self._sampled_num_candidates: int = 0
+ self._round_sampled = False
+
+ @property
+ def dynamic(self) -> bool:
+ """Adapters opt into deferred rounds after supplying their policy."""
+ return False
+
+ @property
+ def sampled_trees(self) -> bool:
+ """Whether this drafter records q for sampled tree proposals."""
+ return self._sampled_q is not None
+
+ @override
+ def bind_sampling_backend(self, sampling_backend: SamplingBackend) -> None:
+ self._sampling_backend = sampling_backend
+ if sampling_backend.supports_tree_sampler:
+ from eagle_harness.tokenspeed.tree_rejection import TreeRejectionSampler
+
+ sampling_backend.bind_tree_sampler(TreeRejectionSampler)
+ if not self.dynamic:
+ super().bind_sampling_backend(sampling_backend)
+
+ def enable_sampled_trees(self, *, num_candidates: int, seed: int) -> None:
+ """Enable reference sampled proposals after binding the dynamic tree.
+
+ Call before graph capture, after ``bind_sampling_backend``. The draft
+ head must provide fp32 ``next_token_logits`` and int64 ``candidate_ids``
+ of width ``num_candidates`` alongside the deterministic top-K scores.
+ ``seed`` selects the proposal Philox stream; the verifier owns its coins.
+ """
+ if not self.dynamic or self.tree_spec is None or self.policy is None:
+ raise ValueError("sampled trees require a bound dynamic tree")
+ if self._depth_graphs or self._pending is not None or self.sampled_trees:
+ raise RuntimeError("enable sampled trees once, before capture or serving")
+ from eagle_harness.tokenspeed.hooks import sampled_hook_problems
+
+ problems = sampled_hook_problems()
+ if problems:
+ raise ValueError("sampled trees require engine hooks: " + "; ".join(problems))
+ backend = self._sampling_backend
+ if backend is None or not backend.verifies_draft_tree_q:
+ raise ValueError("sampled trees require a verifier of recorded tree q")
+ config = self.tree_spec.config
+ if not config.topk <= num_candidates <= 1024:
+ raise ValueError(
+ f"sampled trees need {config.topk} <= num_candidates <= 1024, "
+ f"got {num_candidates}"
+ )
+ self._pools = backend.speculative_sampling_pools()
+ self._sampled_seed = seed
+ self._sampled_num_candidates = num_candidates
+ self._allocate_sampled(
+ self.input_buffers.max_bs,
+ config.topk,
+ config.num_steps,
+ config.num_nodes,
+ self._pool["tokens"].shape[1],
+ num_candidates,
+ )
+
+ def prepare_round_sampling(
+ self, sampling_params_list: list[SamplingParams]
+ ) -> None:
+ """Prepare the live request mix before eager forward or graph replay.
+
+ The caller must first complete any pending round. Sampling requests use
+ the policy's depth planned from earlier rounds, before this round draws.
+ """
+ live = [] if self.input_buffers.all_extends_mid_chunk else sampling_params_list
+ self._round_sampled = self.sampled_trees and any(
+ params.top_k != 1 for params in live
+ )
+ if self.sampled_trees:
+ self._open_round(len(live))
+
+ def bind_dynamic_tree(self, tree_spec, policy: DevicePolicy) -> None:
+ """Bind tree lanes and an already constructed device policy before capture."""
+ config = tree_spec.config
+ allowed_topk = (1,) if policy.chain else (2, 4, 8)
+ max_bs = 512 if policy.chain else 32
+ if config.topk not in allowed_topk or config.num_steps < 2:
+ raise ValueError(
+ f"device-policy rounds need top-k {allowed_topk} and at least two steps"
+ )
+ if self.input_buffers.max_bs > max_bs:
+ raise ValueError(f"device-policy rounds support at most {max_bs} requests")
+ self.bind_tree_lanes(tree_spec)
+ logits_processor = self.draft_model_runner.model.logits_processor
+ logits_processor.do_argmax = False
+ self.tree_vocab_size = logits_processor.config.vocab_size
+ self.policy = policy
+ self._allocate(
+ self.input_buffers.max_bs,
+ config.topk,
+ config.num_steps,
+ max(1024, config.topk * config.topk * config.num_steps),
+ max(64, config.topk * (config.num_steps + 1) + 1),
+ )
+
+ def round_candidates(self, logits_output):
+ """Rank native EAGLE-3 logits and map reduced-vocabulary ids once."""
+ from tokenspeed_kernel.ops.sampling.triton import logprob_topk
+
+ log_probs, tokens = logprob_topk(
+ logits_output.next_token_logits, self.lanes_per_request
+ )
+ if self.sampled_trees:
+ logits, ids = torch.topk(
+ logits_output.next_token_logits, self._sampled_num_candidates, dim=-1
+ )
+ logits_output.next_token_logits = logits.float()
+ logits_output.candidate_ids = self._map_hot(ids)
+ return log_probs.exp(), self._map_hot(tokens)
+
+ def _allocate_sampled(
+ self,
+ max_bs: int,
+ topk: int,
+ depth: int,
+ num_nodes: int,
+ pool_nodes: int,
+ num_candidates: int,
+ ) -> None:
+ """Sampled trees' round buffers and the next round's q tables: one q
+ slot for the root and one per lane row of every later depth."""
+ from tokenspeed.runtime.sampling.tree_verify import DraftTreeQ
+
+ device = self.device
+ num_slots = 1 + (depth - 1) * topk
+ self._sampled_q = DraftTreeQ.zeros(
+ max_bs, num_slots, num_candidates, pool_nodes, device
+ )
+ self._sampled = {
+ "round": torch.zeros((1,), dtype=torch.int64, device=device),
+ "temperature": torch.zeros((max_bs,), dtype=torch.float32, device=device),
+ "top_k": torch.ones((max_bs,), dtype=torch.int32, device=device),
+ "top_p": torch.ones((max_bs,), dtype=torch.float32, device=device),
+ }
+ self.runtime_states.init_draft_tree_q(num_nodes, num_slots, num_candidates)
+
+ def _sample_children(
+ self,
+ logits_output: LogitsProcessorOutput,
+ tokens: torch.Tensor,
+ scores: torch.Tensor,
+ *,
+ width: torch.Tensor | None,
+ slot_base: int,
+ cumu_start: torch.Tensor,
+ launch: int,
+ ) -> None:
+ """Redraw the sampling requests' children of their expanded rows
+ (``tokens`` / ``scores``: ``[bs, rows, K]``, each request's first
+ ``rows`` forwarded rows, of which it expands the first ``width``; None:
+ all) from their draft q, in place; greedy requests keep their top-K."""
+ sampled = self._sampled
+ bs, rows = tokens.shape[:2]
+ if logits_output.candidate_ids is None:
+ raise ValueError("sampled trees require draft candidate_ids")
+ logits, candidates = (
+ output.view(bs, -1, output.shape[-1])[:, :rows]
+ for output in (logits_output.next_token_logits, logits_output.candidate_ids)
+ )
+ eagle_harness_sample_children(
+ logits,
+ candidates,
+ tokens,
+ scores,
+ sampled["temperature"],
+ sampled["top_k"],
+ sampled["top_p"],
+ self._sampled_q.q,
+ self._sampled_q.q_ids,
+ self._sampled_q.slot,
+ self._sampled_q.pos,
+ width,
+ slot_base,
+ cumu_start,
+ self.tree_vocab_size,
+ self._sampled_seed,
+ sampled["round"],
+ launch,
+ )
+
+ def _load_round_sampling(self, bs: int) -> None:
+ """The round's per-request sampling scalars (greedy requests at
+ temperature 0) and a fresh draw counter; tensor-only, in the graph."""
+ pools, sampled = self._pools, self._sampled
+ pool_indices = self.input_buffers.req_pool_indices_buf[:bs]
+ top_k = sampled["top_k"][:bs]
+ torch.index_select(pools.top_k, 0, pool_indices, out=top_k)
+ torch.index_select(pools.top_p, 0, pool_indices, out=sampled["top_p"][:bs])
+ temperature = sampled["temperature"][:bs]
+ torch.index_select(pools.temperature, 0, pool_indices, out=temperature)
+ temperature.masked_fill_(top_k == 1, 0.0)
+ sampled["round"].add_(1)
+
+ def round_depth(self, bs):
+ # A padded graph bucket can replay any smaller live batch, including
+ # batches whose schedule allows a longer chain.
+ widths = [self.policy.table_width(live) for live in range(1, bs + 1)]
+ return max(1, max(widths) - 2) if all(widths) else self.spec_num_steps - 1
+
+ def _allocate(
+ self, max_bs: int, topk: int, depth: int, nodes: int, verify: int
+ ) -> None:
+ """The node pool and lists (``nodes`` nodes, work lists for ``verify``),
+ initialized like the reference's, and the round buffers ``draft`` and
+ ``finish_round`` share."""
+ device = self.device
+ scores = torch.ones((max_bs, nodes), dtype=torch.float32, device=device)
+ scores[:, 0] = _ROOT_SCORE
+ depths = torch.zeros((max_bs, nodes), dtype=torch.int64, device=device)
+ depths[:, 1 : topk + 1] = 1
+ prev = torch.full((max_bs, nodes), -1, dtype=torch.int64, device=device)
+ prev[:, 1 : topk + 1] = 0
+ nxt = torch.full((max_bs, nodes), -1, dtype=torch.int64, device=device)
+ nxt[:, 0] = 1
+ side = torch.full((max_bs, nodes), -1, dtype=torch.int64, device=device)
+ side[:, 1:topk] = torch.arange(2, topk + 1, device=device)
+ work = torch.zeros((max_bs, verify + topk), dtype=torch.float32, device=device)
+ work[:, 0] = _ROOT_SCORE
+ sort = torch.zeros((max_bs, verify), dtype=torch.float32, device=device)
+ sort[:, 0] = _ROOT_SCORE
+ self._pool = {
+ "tokens": torch.zeros((max_bs, nodes), dtype=torch.int64, device=device),
+ "scores": scores,
+ "depths": depths,
+ "prev": prev,
+ "next": nxt,
+ "side": side,
+ "work": work,
+ "sort": sort,
+ }
+
+ hidden_size = self.draft_model_runner.model.config.hidden_size
+ dtype = self.draft_model_runner.model_config.dtype
+ int64 = {"dtype": torch.int64, "device": device}
+ float32 = {"dtype": torch.float32, "device": device}
+ self._round = {
+ # The frontier: its rows' tokens, path scores and input hidden rows.
+ "tokens": torch.zeros((max_bs, topk), **int64),
+ "scores": torch.zeros((max_bs, topk), **float32),
+ "hidden": torch.zeros(
+ (max_bs, topk, hidden_size), dtype=dtype, device=device
+ ),
+ # The accepted frontier (lane slot 0) and the lanes' positions and slots.
+ "frontier": torch.zeros((max_bs,), **int64),
+ "positions": torch.zeros((max_bs * topk,), **int64),
+ "slot_starts": torch.zeros((max_bs,), **int64),
+ "root_tokens": torch.zeros((max_bs,), dtype=torch.int32, device=device),
+ # Frontier pool indices, ping-ponged between consecutive depths.
+ "frontier_index": torch.zeros((2, max_bs, topk), **int64),
+ # The round's requests' rows of the next round's inputs.
+ "rows": torch.zeros((max_bs,), **int64),
+ # Live requests, which a graph's batch statistics read past its padding.
+ "live_rows": torch.zeros((1,), dtype=torch.int32, device=device),
+ "sampled": torch.zeros((1,), dtype=torch.bool, device=device),
+ # The root's first child's pool index, where depth 0's children start.
+ "first_child": torch.ones((1,), dtype=torch.int32, device=device),
+ # By depth parity: a depth's decision reads the previous depth's deltas.
+ "work_deltas": torch.zeros((2, topk + 1), **float32),
+ # The ranked pool: each request's best nodes and their scores.
+ "top_scores": torch.zeros(
+ (max_bs, self.policy.verify_num_limit), **float32
+ ),
+ "top_index": torch.zeros((max_bs, self.policy.verify_num_limit), **int64),
+ }
+ self._live_rows = 0
+ self._live_sampled = False
+ # Depth 1's frontier: the root's children, pool nodes 1..K.
+ self._root_children = (torch.arange(topk, device=device) + 1).repeat(max_bs, 1)
+ # Depth 1's lane masks: lane r sees its own slot r (bit r of word 0).
+ seed = torch.zeros((topk, 1), **int64)
+ seed[:, :1] = (1 << torch.arange(topk, device=device))[:, None]
+ self._tree_seed_lane_mask = seed
+ self._depth_done = [torch.cuda.Event() for _ in range(depth)]
+ self._decide_stream = torch.cuda.Stream(device=device)
+ self._round_stream = torch.cuda.Stream(device=device)
+ self._target_done = torch.cuda.Event()
+ self._round_done = torch.cuda.Event()
+ if isinstance(self.policy, DevicePolicy):
+ self._chain = DeviceChain(max_bs, depth - 1, device)
+
+ @override
+ def draft(self, draft_input: EagleDraftInput) -> torch.Tensor:
+ """The round's first step, the root's children and depth 1's lanes; the
+ next round's inputs are the root alone until ``finish_round`` writes
+ the tree."""
+ if not self.dynamic:
+ return super().draft(draft_input)
+ bs = draft_input.accept_lengths.shape[0]
+ k = self.lanes_per_request
+ pool, state = self._pool, self._round
+
+ next_tokens = self._last_verified_window(bs, draft_input)
+ self.tree_spec.draft_parent_buf[:bs].copy_(self.tree_spec.chain_parent)
+
+ frontier = self._accepted_frontier(bs, draft_input)
+ narrowing = AcceptedPrefixPublisher(self.attn_backend, frontier)
+ logits_output, _ = self._run_first_step(bs, draft_input, narrowing)
+
+ # Depth 1: the root's K best children (head softmax, best first).
+ top_p, top_tokens = self.round_candidates(logits_output)
+ # Policy frontiers use int64; input-buffer cache lengths use int32.
+ state["frontier"][:bs].copy_(frontier)
+ if self.sampled_trees:
+ # The sampled plan must precede the current round's random proposals.
+ self.policy.begin_round(
+ state["live_rows"], state["frontier"][:bs], state["sampled"]
+ )
+ self._load_round_sampling(bs)
+ self._sample_children(
+ logits_output,
+ top_tokens[:, None],
+ top_p[:, None],
+ width=None,
+ slot_base=0,
+ cumu_start=state["first_child"],
+ launch=0,
+ )
+ pool["tokens"][:bs, 0] = next_tokens[:, 0]
+ eagle_harness_update_node_data(
+ pool["scores"][:bs],
+ pool["tokens"][:bs],
+ pool["work"][:bs],
+ pool["sort"][:bs],
+ top_p,
+ top_tokens,
+ )
+ state["root_tokens"][:bs].copy_(next_tokens[:, 0])
+ state["tokens"][:bs].copy_(top_tokens)
+ state["scores"][:bs].copy_(top_p)
+ state["hidden"][:bs].copy_(
+ logits_output.hidden_states[:, None, :].expand(-1, k, -1)
+ )
+ # The next forward refills the input buffers before the round completes.
+ state["rows"][:bs].copy_(
+ self.input_buffers.state_write_req_pool_indices_buf[:bs]
+ )
+ self._start_lanes(bs, bs)
+ return next_tokens
+
+ @override
+ def replay_decode_graph(
+ self, graph: torch.cuda.CUDAGraph, *, bs: int, graph_bs: int
+ ) -> None:
+ """With device-chained rounds, replay the decode graph on the round
+ stream and launch its round's depth 1 behind it: the forward's stream
+ waits for the decode graph alone, so its outputs and the next
+ forward's staging run beside the round."""
+ if self._chain is None or bs == 0:
+ graph.replay()
+ return
+ if self._launched_rows is not None:
+ raise RuntimeError(
+ "EAGLE-Harness decode graph replayed before finish_round booked the round the last replay launched"
+ )
+ self._check_round_graphs(bs, graph_bs)
+ self._open_round(bs)
+ stream, round_stream = torch.cuda.current_stream(), self._round_stream
+ round_stream.wait_stream(stream)
+ with torch.cuda.stream(round_stream):
+ graph.replay()
+ self._target_done.record()
+ self._launch_chain(graph_bs)
+ stream.wait_event(self._target_done)
+ self._launched_rows = graph_bs
+
+ @maybe_inference_mode()
+ def finish_round(self, ctx, graph_bs):
+ if not self.dynamic:
+ return
+ bs = ctx.bs
+ launched, self._launched_rows = self._launched_rows, None
+ if bs == 0 or self.input_buffers.all_extends_mid_chunk:
+ return
+ chained = self._chain is not None and graph_bs is not None
+ if chained and launched is None:
+ self._check_round_graphs(bs, graph_bs)
+ self._round_seq += 1
+ self._pending = pending = _PendingRound(
+ ctx=ctx,
+ stream=torch.cuda.current_stream(),
+ bs=bs,
+ rows=bs if graph_bs is None else graph_bs,
+ graphs=graph_bs is not None,
+ seq=self._round_seq,
+ sampled=self._round_sampled,
+ chained=chained,
+ )
+ if launched is not None:
+ if launched != pending.rows:
+ raise RuntimeError("decode and draft graph batch sizes differ")
+ return
+ self._open_round(bs)
+ if ctx.num_extends > 0 and graph_bs is not None and graph_bs > bs:
+ self._pad_round_rows(bs, graph_bs)
+ self._round_stream.wait_stream(pending.stream)
+ with torch.cuda.stream(self._round_stream):
+ if chained:
+ self._launch_chain(pending.rows)
+ else:
+ self._launch_depth(pending, 1)
+ self._advance(pending, pause_before_wait=True)
+
+ def _check_round_graphs(self, bs: int, rows: int) -> None:
+ """Refuse a device-chained round of ``bs`` requests on padded batch
+ ``rows`` that could reach a depth the batch did not capture."""
+ depth = self.round_depth(bs)
+ if (rows, depth) not in self._depth_graphs:
+ raise RuntimeError(
+ f"EAGLE-Harness round of {bs} requests can draft depth {depth}, "
+ f"which its padded batch {rows} did not capture (round_depth)"
+ )
+
+ def _launch_chain(self, rows: int) -> None:
+ """Launch a device-chained round's depth 1 on the current stream,
+ which orders its later work after the round."""
+ self._depth_graphs[(rows, 1)].replay()
+ self._round_done.record()
+
+ def _open_round(self, bs: int) -> None:
+ """Before the round's depth 1, on the forward's stream: its live
+ requests and sampled flag (written on change), and the policy's batch
+ size."""
+ state = self._round
+ if bs != self._live_rows:
+ state["live_rows"].fill_(bs)
+ self._live_rows = bs
+ if self._round_sampled != self._live_sampled:
+ state["sampled"].fill_(self._round_sampled)
+ self._live_sampled = self._round_sampled
+ self.policy.observe_batch_size(bs)
+
+ def _pad_round_rows(self, bs: int, rows: int) -> None:
+ """Rows ``bs .. rows`` of an extend's round that replays graphs at
+ ``rows``: no children, one cached key and the null page, so their
+ lanes read and write only the dummy page, as a padded decode graph's
+ padding rows do."""
+ pool, state = self._pool, self._round
+ pad = slice(bs, rows)
+ if self.sampled_trees:
+ self._sampled["temperature"][pad].zero_()
+ self._sampled["top_k"][pad].fill_(1)
+ self._sampled["top_p"][pad].fill_(1.0)
+ state["tokens"][pad].zero_()
+ state["scores"][pad].zero_()
+ state["hidden"][pad].zero_()
+ state["root_tokens"][pad].zero_()
+ pool["tokens"][pad, 0].zero_()
+ eagle_harness_update_node_data(
+ pool["scores"][pad],
+ pool["tokens"][pad],
+ pool["work"][pad],
+ pool["sort"][pad],
+ state["scores"][pad],
+ state["tokens"][pad],
+ )
+ state["frontier"][pad].fill_(1)
+ state["rows"][pad].fill_(self.input_buffers.state_write_padding_pool_index)
+ self._start_lanes(rows, bs)
+
+ @override
+ def has_round_graphs(self, graph_bs: int) -> bool:
+ # Exec mode 2 drafts extends eagerly: it measures only decode rounds.
+ return self.dynamic and (graph_bs, False) in self._finalize_graphs
+
+ @override
+ @maybe_inference_mode()
+ def complete_round(self) -> None:
+ """Draft the rest of the pending round, then rank its pool and write
+ its verify tree into the next round's inputs (a device-chained round
+ does all this on the GPU), and order the round's forward stream after
+ it.
+
+ The rest runs on the round stream, so the outputs and the next
+ forward's inputs and attention metadata queued on the forward's stream
+ since ``finish_round`` run beside the depths instead of between them.
+ """
+ pending = self._pending
+ if pending is None:
+ return
+ self._pending = None
+ if not pending.chained:
+ with torch.cuda.stream(self._round_stream):
+ self._advance(pending, pause_before_wait=False)
+ self._finalize(pending)
+ pending.stream.wait_stream(self._round_stream)
+ # Non-forward device tasks can enter on another stream before reusing a slot.
+ torch.cuda.current_stream().wait_stream(self._round_stream)
+
+ def _advance(self, pending: _PendingRound, *, pause_before_wait: bool) -> None:
+ """Launch each next depth the policy decides to draft, until the round
+ stops (or, with ``pause_before_wait``, until a decision has not landed
+ yet). A depth's decision runs at its start beside its forward, so the
+ host learns whether to launch the next depth while the GPU drafts it;
+ a width-table round's depths are known up front and launch at once."""
+ policy = self.policy
+ while True:
+ depth = pending.depth
+ go = policy.go_ready(depth + 1, pending.seq)
+ if go is None:
+ if pause_before_wait:
+ return
+ go = self._wait_decision(pending, depth)
+ if not go:
+ return
+ pending.depth = depth + 1
+ self._launch_depth(pending, depth + 1)
+
+ def _wait_decision(self, pending: _PendingRound, depth: int) -> bool:
+ """Whether depth ``depth + 1`` drafts: once ``depth`` has started, its
+ decision lands within microseconds, so poll the go flag until then."""
+ self._depth_done[depth - 1].synchronize()
+ done = self._depth_done[depth]
+ while True:
+ # Queried first: a finished depth has published its decision.
+ finished = done.query()
+ go = self.policy.go_ready(depth + 1, pending.seq)
+ if go is not None:
+ return go
+ if finished:
+ raise RuntimeError(
+ f"EAGLE-Harness round {pending.seq} has no decision after depth {depth}"
+ )
+
+ def _launch_depth(self, pending: _PendingRound, depth: int) -> None:
+ """Draft ``depth`` and its decision (its captured graph, or eagerly),
+ and mark where it ends."""
+ if depth == 1:
+ self._depth_done[0].record()
+ if pending.graphs:
+ graph = self._depth_graphs.get((pending.rows, depth))
+ if graph is None:
+ raise RuntimeError(
+ f"EAGLE-Harness round of {pending.bs} requests drafts depth "
+ f"{depth}, which its padded batch {pending.rows} did not "
+ "capture (round_depth)"
+ )
+ graph.replay()
+ else:
+ ctx = pending.ctx
+ lanes = self._lane_context(
+ pending.rows,
+ ctx.global_num_tokens,
+ ctx.global_bs,
+ ctx.all_decode_or_idle,
+ )
+ with self.attn_backend.override_num_extends(0):
+ self._draft_depth(pending.rows, lanes, depth, decide=True, chain=False)
+ self._depth_done[depth].record()
+
+ def _start_lanes(self, rows: int, live_rows: int) -> None:
+ """Depth 1's lane positions and slots (the accepted frontier) and lane
+ masks; rows past ``live_rows`` are padding (null page)."""
+ state, lanes = self._round, self.tree_lanes
+ self.attn_backend.begin_tree_lanes(rows, live_rows)
+ frontier = state["frontier"][:rows]
+ lanes.set_frontier(rows, frontier)
+ k, words = self.lanes_per_request, 1
+ state["positions"][: rows * k].view(rows, k).copy_(
+ frontier[:, None].expand(-1, k)
+ )
+ state["slot_starts"][:rows].copy_(frontier)
+ lanes.lane_mask[: rows * k * words].view(rows, k, words).copy_(
+ self._tree_seed_lane_mask
+ )
+
+ def _queue_work_deltas(self, rows: int, depth: int) -> None:
+ """Depth ``depth``'s work deltas over the live rows among ``rows``, at
+ the depths whose slot can ask for them (its work size; 0: none)."""
+ policy = self.policy
+ if not policy.deltas_depth(depth):
+ return
+ eagle_harness_work_deltas(
+ self._pool["work"][:rows],
+ self._round["work_deltas"][depth % 2],
+ self._round["live_rows"],
+ policy.work_sizes[depth : depth + 1],
+ self.lanes_per_request,
+ policy.past_verify_num,
+ )
+
+ @override
+ @maybe_inference_mode()
+ def capture_round_graphs(
+ self, graph_bs: int, *, lo_bs: int, stream: torch.cuda.Stream, pool
+ ) -> None:
+ """Capture each draft depth at the decode graph's padded batch: its
+ widths, pool sizes and work list sizes are device slots, so one graph
+ per depth serves every round. Only the depths the rounds of ``lo_bs +
+ 1`` to ``graph_bs`` live requests (those the batch pads) can reach.
+ A device chain's depths launch the round's next graph after their
+ decision; depths 2 and on and the finalize are instantiated for device
+ launch."""
+ if not self.dynamic:
+ return
+ depths = max(self.round_depth(bs) for bs in range(lo_bs + 1, graph_bs + 1))
+ lanes = self._lane_context(graph_bs, None, None, True)
+ chain = self._chain
+ with torch.cuda.stream(stream), self.attn_backend.override_num_extends(0):
+ # Warm up on a full round, without the decisions whose state the rounds own.
+ self.policy.write_full_round()
+ self._start_lanes(graph_bs, graph_bs)
+ for depth in range(1, depths + 1):
+ self._draft_depth(graph_bs, lanes, depth, decide=False, chain=False)
+ torch.cuda.synchronize()
+ # The host launches depth 1 (an ordinary graph); the GPU, the rest.
+ graph = torch.cuda.CUDAGraph(keep_graph=chain is not None and depth > 1)
+ with torch.cuda.graph(graph, pool=pool, stream=stream):
+ self._draft_depth(
+ graph_bs, lanes, depth, decide=True, chain=chain is not None
+ )
+ self._depth_graphs[(graph_bs, depth)] = graph
+ samples = (False, True) if self.sampled_trees else (False,)
+ for sampled in samples:
+ graph = torch.cuda.CUDAGraph(keep_graph=chain is not None)
+ with torch.cuda.graph(graph, pool=pool, stream=stream):
+ self._write_verify_tree(graph_bs, sampled)
+ self._finalize_graphs[(graph_bs, sampled)] = graph
+ if chain is not None:
+ chain.instantiate(
+ graph_bs,
+ [self._depth_graphs[(graph_bs, d)] for d in range(2, depths + 1)],
+ [self._finalize_graphs[(graph_bs, sampled)] for sampled in samples],
+ stream,
+ )
+ if self.sampled_trees:
+ self._sampled["round"].zero_()
+
+ @override
+ def release_round_graphs(self) -> None:
+ if self._chain is not None:
+ self._chain.release()
+ self._depth_graphs.clear()
+ self._finalize_graphs.clear()
+
+ def _lane_context(
+ self,
+ bs: int,
+ global_num_tokens: list[int] | None,
+ global_bs: list[int] | None,
+ all_decode_or_idle: bool,
+ ) -> ForwardContext:
+ """The forward context of a depth's ``K`` lanes per request."""
+ k = self.lanes_per_request
+ return ForwardContext(
+ bs=bs,
+ num_extends=0,
+ output_layout=ForwardOutputLayout(0, 0, bs, k),
+ attn_backend=self.attn_backend,
+ token_to_kv_pool=self.token_to_kv_pool,
+ input_num_tokens=bs * k,
+ forward_mode=ForwardMode.DECODE,
+ capture_hidden_mode=CaptureHiddenMode.LAST,
+ global_num_tokens=global_num_tokens,
+ global_bs=global_bs,
+ all_decode_or_idle=all_decode_or_idle,
+ )
+
+ def _draft_depth(
+ self, bs: int, lanes: ForwardContext, depth: int, *, decide: bool, chain: bool
+ ) -> None:
+ """Forward depth ``depth``'s frontier (lane slots ``(depth - 1) * K``
+ on) and append the ``K`` best children of each row's ``widths[depth]``
+ best frontier nodes to the pool from ``cumu_starts[depth]`` on; leaves
+ the next frontier in the round buffers. With ``decide``, the decision
+ after ``depth`` (which reads only the previous depth's work deltas)
+ runs beside the forward, after the round's start at depth 1; with
+ ``chain`` (a captured depth of a device chain), the launch of the
+ round's next graph follows that decision there, off the forward's
+ path, and starts once this depth's graph has ended.
+
+ All ``K`` lanes forward; past the width their outputs are dropped, and
+ their K/V (in their own lane slots) is no node's ancestor. The lane
+ masks this depth's forward reads come from the previous depth's
+ update (depth 1's from ``_start_lanes``).
+ """
+ k, policy = self.lanes_per_request, self.policy
+ pool, state, tree_lanes = self._pool, self._round, self.tree_lanes
+ width = policy.widths[depth : depth + 1]
+ cumu_start = policy.cumu_starts[depth : depth + 1]
+ stream, decide_stream = torch.cuda.current_stream(), self._decide_stream
+ if decide:
+ decide_stream.wait_stream(stream)
+ with torch.cuda.stream(decide_stream):
+ if depth == 1:
+ if not self.sampled_trees:
+ policy.begin_round(
+ state["live_rows"], state["frontier"][:bs], state["sampled"]
+ )
+ # Depth 0 weighs the root (one node) against its K children.
+ self._queue_work_deltas(bs, 0)
+ policy.decide(depth, state["work_deltas"][(depth - 1) % 2])
+ if chain:
+ self._chain.end_depth(bs, depth, policy.go, state["sampled"])
+ tree_lanes.active = True
+ tree_lanes.step = depth
+ self.attn_backend.publish_draft_step_locations(
+ cache_start=state["slot_starts"][:bs], num_tokens=k
+ )
+ logits_output = self.draft_model_runner.forward(
+ ctx=lanes,
+ input_ids=state["tokens"][:bs].view(-1),
+ positions=state["positions"][: bs * k],
+ captured_hidden_states=state["hidden"][:bs].view(bs * k, -1),
+ spec_step_idx=depth,
+ )
+ tree_lanes.active = False
+ if decide and depth == 1:
+ # Depth 1's counts come from the round's start.
+ stream.wait_stream(decide_stream)
+ # The lanes' children; each request expands its first ``width`` rows.
+ child_p, child_tokens = (
+ output.view(bs, k, k) for output in self.round_candidates(logits_output)
+ )
+ if self.sampled_trees:
+ self._sample_children(
+ logits_output,
+ child_tokens,
+ child_p,
+ width=width,
+ slot_base=1 + (depth - 1) * k,
+ cumu_start=cumu_start,
+ launch=depth,
+ )
+ # Children sit one depth below the frontier the forward expanded.
+ expanded = (
+ self._root_children[:bs]
+ if depth == 1
+ else state["frontier_index"][(depth + 1) % 2][:bs]
+ )
+ words = 1
+ eagle_harness_draft_depth_update(
+ child_p,
+ child_tokens,
+ expanded,
+ logits_output.hidden_states.view(bs, k, -1),
+ state["tokens"][:bs],
+ state["scores"][:bs],
+ state["hidden"][:bs],
+ state["frontier_index"][depth % 2][:bs],
+ pool["tokens"][:bs],
+ pool["scores"][:bs],
+ pool["depths"][:bs],
+ pool["prev"][:bs],
+ pool["next"][:bs],
+ pool["side"][:bs],
+ pool["work"][:bs],
+ pool["sort"][:bs],
+ state["positions"][: bs * k].view(bs, k),
+ state["slot_starts"][:bs],
+ tree_lanes.lane_mask[: bs * k * words].view(bs, k, words),
+ width,
+ depth,
+ cumu_start,
+ policy.past_verify_num,
+ tree_lanes.num_slots,
+ )
+ self._queue_work_deltas(bs, depth)
+ if decide and depth > 1:
+ stream.wait_stream(decide_stream)
+
+ def _finalize(self, pending: _PendingRound) -> None:
+ """Rank the pool and write the verify tree (its captured graph, or
+ eagerly, as when the policy's select_verify waits on the host)."""
+ if pending.graphs and not self.policy.eager_select_verify:
+ self._finalize_graphs[(pending.rows, pending.sampled)].replay()
+ else:
+ self._write_verify_tree(pending.rows, pending.sampled)
+
+ def _write_verify_tree(self, bs: int, sampled: bool) -> None:
+ """Rank the pool of the live rows among ``bs``, size the verify, and
+ write the verify tree as the next round's inputs: the best nodes in
+ ancestor-first score order, root first; unused slots repeat the root
+ with parent -1 and are never accepted.
+
+ All on the device: the verify size reads the previous round's ranked
+ scores (the first round its own), and this round's wait there for the
+ next.
+ """
+ pool, policy, state = self._pool, self.policy, self._round
+ live_rows = state["live_rows"]
+ top_scores, top_index = state["top_scores"][:bs], state["top_index"][:bs]
+ eagle_harness_stable_topk_desc(
+ pool["scores"][:bs],
+ live_rows,
+ policy.cumu_count,
+ policy.verify_count,
+ top_scores,
+ top_index,
+ )
+ policy.select_verify(top_scores)
+ eagle_harness_write_verify_tree(
+ top_index,
+ pool["tokens"][:bs],
+ pool["prev"][:bs],
+ state["root_tokens"][:bs],
+ state["rows"][:bs],
+ self.runtime_states.future_input_map,
+ self.runtime_states.future_parent_map,
+ live_rows,
+ policy.verify_num,
+ )
+ if sampled:
+ draft_q, round_q = self.runtime_states.future_draft_q, self._sampled_q
+ eagle_harness_publish_draft_q(
+ top_index,
+ round_q.slot[:bs],
+ round_q.pos[:bs],
+ round_q.q[:bs],
+ round_q.q_ids[:bs],
+ state["rows"][:bs],
+ draft_q.q,
+ draft_q.q_ids,
+ draft_q.slot,
+ draft_q.pos,
+ live_rows,
+ policy.verify_num,
+ )
+
+ def _last_verified_window(
+ self, bs: int, draft_input: EagleDraftInput
+ ) -> torch.Tensor:
+ """The next verify window, every column the request's last verified id."""
+ next_tokens = torch.empty(
+ (bs, self.spec_num_tokens),
+ dtype=torch.int32,
+ device=self.device,
+ )
+
+ # Last verified id per request → next_tokens[:, 0].
+ num_extends = draft_input.num_extends
+ num_decodes = bs - num_extends
+ if num_extends > 0:
+ next_tokens[:num_extends, 0] = draft_input.base_model_output[:num_extends]
+ if num_decodes > 0:
+ indices = (
+ self.padded_gather_ids_offsets_buf[:num_decodes]
+ + draft_input.accept_lengths[num_extends:]
+ )
+ if num_extends > 0:
+ indices.add_(num_extends)
+ torch.index_select(
+ draft_input.base_model_output,
+ 0,
+ indices,
+ out=next_tokens[num_extends:, 0],
+ )
+ if self.spec_num_tokens > 1:
+ next_tokens[:, 1:] = next_tokens[:, :1]
+ return next_tokens
diff --git a/eagle_harness/tokenspeed/tree_round/ops/__init__.py b/eagle_harness/tokenspeed/tree_round/ops/__init__.py
new file mode 100644
index 0000000..75676e7
--- /dev/null
+++ b/eagle_harness/tokenspeed/tree_round/ops/__init__.py
@@ -0,0 +1,4 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""CUDA tree, device policy and graph launch chain operations, loaded lazily."""
diff --git a/eagle_harness/tokenspeed/tree_round/ops/build.py b/eagle_harness/tokenspeed/tree_round/ops/build.py
new file mode 100644
index 0000000..61353cb
--- /dev/null
+++ b/eagle_harness/tokenspeed/tree_round/ops/build.py
@@ -0,0 +1,192 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Build the packaged TokenSpeed CUDA sources without partner prebuilt binaries.
+
+Uses the native kernel builder's nvcc discovery and atomic publication pattern.
+TVM FFI supplies tensor/stream interop; torch and Python headers are not needed.
+``python -m eagle_harness.tokenspeed.tree_round.ops.build --arch 103 --output ./build/round-ops``
+compiles all four modules without accessing a GPU. Runtime builds are cached
+by source, toolkit, architecture and TVM FFI ABI, before graph capture.
+"""
+
+from __future__ import annotations
+
+import argparse
+import functools
+import hashlib
+import importlib.metadata
+import os
+import subprocess
+import tempfile
+from pathlib import Path
+
+from eagle_harness.kernels.build import find_nvcc, toolkit_version
+
+SOURCE = Path(__file__).resolve().parent / "csrc"
+MODULES = ("tree", "policy", "chain", "rejection")
+NVCC_FLAGS = (
+ "-O3",
+ "-std=c++17",
+ "--expt-relaxed-constexpr",
+ "--fmad=false",
+ "-Xcompiler=-fPIC",
+)
+
+
+def _ffi_paths() -> tuple[list[str], str]:
+ try:
+ from tvm_ffi import libinfo
+ except ImportError as exc:
+ raise RuntimeError(
+ "TokenSpeed device kernels require apache-tvm-ffi (provided by TokenSpeed)"
+ ) from exc
+ return [
+ libinfo.find_include_path(),
+ libinfo.find_dlpack_include_path(),
+ ], libinfo.find_libtvm_ffi()
+
+
+def compile_library(name: str, out: Path, arch: int, nvcc: str | None = None) -> Path:
+ """Compile and atomically publish one library; no GPU or torch import."""
+ if name not in MODULES:
+ raise ValueError(f"Unknown TokenSpeed kernel module: {name!r}")
+ nvcc = nvcc or find_nvcc()
+ if nvcc is None:
+ raise RuntimeError("nvcc not found (set CUDA_HOME to a CUDA 12+ toolkit)")
+ if toolkit_version(nvcc) < (12, 0):
+ raise RuntimeError("TokenSpeed device graph launches require CUDA 12+")
+ if arch < 80:
+ raise ValueError(
+ "TokenSpeed device policy requires compute capability 8.0 or newer"
+ )
+ includes, ffi_library = _ffi_paths()
+ include_flags = [f"-I{SOURCE}", *(f"-I{p}" for p in includes)]
+ gencode = [
+ f"-gencode=arch=compute_{arch},code=sm_{arch}",
+ f"-gencode=arch=compute_{arch},code=compute_{arch}",
+ ]
+ out = Path(out)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(dir=out.parent, prefix=f".{name}-") as tmp:
+ obj = Path(tmp) / f"{name}.o"
+ commands = [
+ [
+ nvcc,
+ *NVCC_FLAGS,
+ *gencode,
+ *include_flags,
+ *(["-rdc=true"] if name == "chain" else []),
+ "-c",
+ str(SOURCE / f"eagle_harness_{name}.cu"),
+ "-o",
+ str(obj),
+ ]
+ ]
+ objects = [str(obj)]
+ if name == "chain":
+ dlink = Path(tmp) / "device_link.o"
+ commands.append(
+ [
+ nvcc,
+ *gencode,
+ "-Xcompiler=-fPIC",
+ "-dlink",
+ str(obj),
+ "-lcudadevrt",
+ "-o",
+ str(dlink),
+ ]
+ )
+ objects.append(str(dlink))
+ partial = Path(tmp) / out.name
+ commands.append(
+ [
+ nvcc,
+ "-shared",
+ "-Xcompiler=-fPIC",
+ *objects,
+ "-cudart=static",
+ *(["-lcudadevrt"] if name == "chain" else []),
+ ffi_library,
+ f"-Xlinker=-rpath={Path(ffi_library).parent}",
+ "-o",
+ str(partial),
+ ]
+ )
+ for command in commands:
+ result = subprocess.run(
+ command, capture_output=True, text=True, check=False
+ )
+ if result.returncode:
+ raise RuntimeError(
+ f"nvcc failed: {' '.join(command)}\n{result.stdout[-2000:]}\n{result.stderr[-6000:]}"
+ )
+ partial.chmod(0o755)
+ os.replace(partial, out)
+ return out
+
+
+def _load(name: str, arch: int):
+ import torch
+ import tvm_ffi
+
+ from eagle_harness.kernels.native import _cache_dir
+
+ nvcc = find_nvcc()
+ if nvcc is None:
+ raise RuntimeError(
+ "nvcc not found (set CUDA_HOME); TokenSpeed kernel sources need a CUDA toolkit"
+ )
+ includes, ffi_library = _ffi_paths()
+ identity = repr(
+ (
+ arch,
+ nvcc,
+ toolkit_version(nvcc),
+ NVCC_FLAGS,
+ importlib.metadata.version("apache-tvm-ffi"),
+ includes,
+ ffi_library,
+ )
+ ).encode()
+ # Hash this build recipe as well as the sources: flag/link changes rebuild.
+ digest = hashlib.sha256(identity + Path(__file__).read_bytes())
+ for path in (SOURCE / f"eagle_harness_{name}.cu", SOURCE / "tvm_ffi_utils.h"):
+ digest.update(path.read_bytes())
+ out = _cache_dir() / "tokenspeed_round" / digest.hexdigest()[:20] / f"{name}.so"
+ if not out.exists():
+ if torch.cuda.is_current_stream_capturing():
+ raise RuntimeError(
+ "Load TokenSpeed device kernels before CUDA graph capture"
+ )
+ compile_library(name, out, arch, nvcc)
+ return tvm_ffi.load_module(str(out))
+
+
+def load_module(name: str):
+ """Load for the current device, with no disk access after the first call."""
+ import torch
+
+ if name not in MODULES:
+ raise ValueError(f"Unknown TokenSpeed kernel module: {name!r}")
+ major, minor = torch.cuda.get_device_capability()
+ return _load(name, major * 10 + minor)
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument(
+ "--arch", type=int, required=True, help="CUDA SM, e.g. 90 or 103"
+ )
+ parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--cuda-home")
+ args = parser.parse_args()
+ nvcc = find_nvcc(args.cuda_home)
+ for name in MODULES:
+ print(compile_library(name, args.output / f"{name}.so", args.arch, nvcc))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/eagle_harness/tokenspeed/tree_round/ops/chain.py b/eagle_harness/tokenspeed/tree_round/ops/chain.py
new file mode 100644
index 0000000..6655a9a
--- /dev/null
+++ b/eagle_harness/tokenspeed/tree_round/ops/chain.py
@@ -0,0 +1,56 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""EAGLE-Harness device-chained rounds (EAGLE-4): CUDA graphs instantiated
+for device launch, and the kernel inside each draft depth's graph that
+tail-launches the round's next graph; see ``csrc/eagle_harness_chain.cu``.
+
+Graph and exec handles are the raw ``cudaGraph_t`` / ``cudaGraphExec_t``
+pointers as integers (``torch.cuda.CUDAGraph(keep_graph=True)``'s
+``raw_cuda_graph()``), streams the raw ``cudaStream_t`` (``cuda_stream``)."""
+
+import torch
+
+from eagle_harness.tokenspeed.tree_round.ops.build import load_module
+
+__all__ = [
+ "eagle_harness_chain_destroy",
+ "eagle_harness_chain_instantiate",
+ "eagle_harness_chain_load",
+ "eagle_harness_chain_next",
+]
+
+
+def eagle_harness_chain_load() -> None:
+ """Load the kernel library (no launch), before a graph capture uses it."""
+ load_module("chain")
+
+
+def eagle_harness_chain_instantiate(graph: int, stream: int) -> int:
+ """Instantiate the captured ``graph`` for device launch and upload it on
+ ``stream``; returns the exec handle (``eagle_harness_chain_destroy``
+ frees it). The graph may hold kernel, memcpy (device or pinned memory)
+ and memset nodes, fork/join edges included; no event, host, memory
+ allocation or conditional nodes, and no dynamic parallelism beyond this
+ module's own launch (CUDA's device graph requirements)."""
+ return load_module("chain").eagle_harness_chain_instantiate(graph, stream)
+
+
+def eagle_harness_chain_destroy(exec_handle: int) -> None:
+ """Free an exec handle no queued or running chain still launches."""
+ load_module("chain").eagle_harness_chain_destroy(exec_handle)
+
+
+def eagle_harness_chain_next(
+ execs: torch.Tensor,
+ go: torch.Tensor,
+ sampled: torch.Tensor,
+ depth: int,
+ last_depth: int,
+) -> None:
+ """Tail-launch depth+1 when go says so, otherwise the greedy finalize.
+
+ execs keeps the partner [last_depth+3] ABI; the final column is reserved.
+ sampled must contain false. A missing handle or sampled round traps.
+ """
+ load_module("chain").eagle_harness_chain_next(execs, go, sampled, depth, last_depth)
diff --git a/eagle_harness/tokenspeed/tree_round/ops/csrc/eagle_harness_chain.cu b/eagle_harness/tokenspeed/tree_round/ops/csrc/eagle_harness_chain.cu
new file mode 100644
index 0000000..f746aa1
--- /dev/null
+++ b/eagle_harness/tokenspeed/tree_round/ops/csrc/eagle_harness_chain.cu
@@ -0,0 +1,149 @@
+// Copyright 2026 Eagle AI Corp.
+// SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+#include <cstdint>
+#include <map>
+#include <sstream>
+#include <string>
+#include <vector>
+
+#include "tvm_ffi_utils.h"
+
+namespace {
+
+// execs (int64 [last_depth + 3]): column d holds depth d's graph exec
+// (2 <= d <= last_depth; 0 where the batch did not capture it), then the
+// greedy and sampled finalizers. go (int32 [>= last_depth + 1]):
+// whether depth d drafts this round, written by depth d - 1's decision.
+__global__ void chain_kernel(const int64_t* __restrict__ execs, const int32_t* __restrict__ go,
+ const bool* __restrict__ sampled, int depth, int last_depth) {
+ const bool deeper = depth < last_depth && go[depth + 1] != 0;
+ const int64_t next = execs[deeper ? depth + 1 : last_depth + 1 + static_cast<int>(*sampled)];
+ // A round reaching a graph its batch did not capture would leave its tree
+ // unwritten: fail loudly instead.
+ if (next == 0 || cudaGraphLaunch(reinterpret_cast<cudaGraphExec_t>(next),
+ cudaStreamGraphTailLaunch) != cudaSuccess) {
+ __trap();
+ }
+}
+
+void check_cuda(cudaError_t status, const char* what) {
+ TVM_FFI_ICHECK(status == cudaSuccess)
+ << "eagle_harness_chain: " << what << ": " << cudaGetErrorString(status);
+}
+
+// What a graph holds that device launch may refuse: its node types (device
+// graphs allow kernel, memcpy, memset and child graph nodes only), memcpy
+// kinds, kernels launched with attributes, and edges that are not plain
+// dependencies. Reported with an instantiate failure, which CUDA otherwise
+// explains as "invalid argument" alone.
+std::string describe_graph(cudaGraph_t graph) {
+ static const char* const kTypes[] = {"kernel", "memcpy", "memset", "host", "child graph", "empty",
+ "event wait", "event record", "semaphore signal",
+ "semaphore wait", "mem alloc", "mem free", "batch mem op",
+ "conditional"};
+ size_t count = 0;
+ if (cudaGraphGetNodes(graph, nullptr, &count) != cudaSuccess) return "";
+ std::vector<cudaGraphNode_t> nodes(count);
+ if (count && cudaGraphGetNodes(graph, nodes.data(), &count) != cudaSuccess) return "";
+ std::map<std::string, int> types;
+ std::map<std::string, int> attributes;
+ for (cudaGraphNode_t node : nodes) {
+ cudaGraphNodeType type;
+ if (cudaGraphNodeGetType(node, &type) != cudaSuccess) continue;
+ std::string name = type < sizeof(kTypes) / sizeof(kTypes[0]) ? kTypes[type]
+ : "type " + std::to_string(type);
+ if (type == cudaGraphNodeTypeMemcpy) {
+ cudaMemcpy3DParms params{};
+ if (cudaGraphMemcpyNodeGetParams(node, &params) == cudaSuccess) {
+ static const char* const kKinds[] = {"host to host", "host to device", "device to host",
+ "device to device", "default"};
+ name += std::string(" ") +
+ (params.kind < 5 ? kKinds[params.kind] : std::to_string(params.kind));
+ }
+ } else if (type == cudaGraphNodeTypeKernel) {
+ cudaLaunchAttributeValue value{};
+ if (cudaGraphKernelNodeGetAttribute(node, cudaLaunchAttributeCooperative, &value) ==
+ cudaSuccess &&
+ value.cooperative)
+ ++attributes["cooperative"];
+ value = {};
+ if (cudaGraphKernelNodeGetAttribute(node, cudaLaunchAttributeProgrammaticStreamSerialization,
+ &value) == cudaSuccess &&
+ value.programmaticStreamSerializationAllowed)
+ ++attributes["programmatic stream serialization"];
+ value = {};
+ if (cudaGraphKernelNodeGetAttribute(node, cudaLaunchAttributeMemSyncDomain, &value) ==
+ cudaSuccess &&
+ value.memSyncDomain != cudaLaunchMemSyncDomainDefault)
+ ++attributes["remote mem sync domain"];
+ }
+ ++types[name];
+ }
+ size_t edges = 0;
+ int typed_edges = 0;
+#if CUDART_VERSION >= 13000
+ auto get_edges = cudaGraphGetEdges;
+#else
+ auto get_edges = cudaGraphGetEdges_v2;
+#endif
+ if (get_edges(graph, nullptr, nullptr, nullptr, &edges) == cudaSuccess && edges) {
+ std::vector<cudaGraphNode_t> from(edges), to(edges);
+ std::vector<cudaGraphEdgeData> data(edges);
+ if (get_edges(graph, from.data(), to.data(), data.data(), &edges) == cudaSuccess)
+ for (const cudaGraphEdgeData& edge : data)
+ if (edge.type != cudaGraphDependencyTypeDefault || edge.from_port || edge.to_port)
+ ++typed_edges;
+ }
+ std::ostringstream out;
+ out << " (graph of " << count << " nodes:";
+ for (const auto& [name, n] : types) out << " " << n << " " << name << ",";
+ for (const auto& [name, n] : attributes) out << " " << n << " kernels " << name << ",";
+ out << " " << edges << " edges, " << typed_edges << " programmatic/ported)";
+ return out.str();
+}
+
+} // namespace
+
+int64_t eagle_harness_chain_instantiate(int64_t graph, int64_t stream) {
+ cudaGraphExec_t exec = nullptr;
+ const cudaError_t instantiated = cudaGraphInstantiateWithFlags(
+ &exec, reinterpret_cast<cudaGraph_t>(graph), cudaGraphInstantiateFlagDeviceLaunch);
+ TVM_FFI_ICHECK(instantiated == cudaSuccess)
+ << "eagle_harness_chain: instantiate for device launch: " << cudaGetErrorString(instantiated)
+ << describe_graph(reinterpret_cast<cudaGraph_t>(graph));
+ const cudaError_t uploaded = cudaGraphUpload(exec, reinterpret_cast<cudaStream_t>(stream));
+ if (uploaded != cudaSuccess) cudaGraphExecDestroy(exec);
+ check_cuda(uploaded, "upload");
+ return reinterpret_cast<int64_t>(exec);
+}
+
+void eagle_harness_chain_destroy(int64_t exec) {
+ check_cuda(cudaGraphExecDestroy(reinterpret_cast<cudaGraphExec_t>(exec)), "destroy");
+}
+
+void eagle_harness_chain_next(TensorView execs, TensorView go, TensorView sampled, int64_t depth,
+ int64_t last_depth) {
+ check_tensor(execs, dl_int64, execs.device());
+ check_tensor(go, dl_int32, execs.device());
+ check_scalar(sampled, dl_bool, execs.device());
+ TVM_FFI_ICHECK(last_depth >= 1 && last_depth <= 31);
+ TVM_FFI_ICHECK(execs.dtype() == dl_int64 && execs.ndim() == 1 && execs.stride(0) == 1 &&
+ execs.size(0) == last_depth + 3)
+ << "eagle_harness_chain: exec table";
+ TVM_FFI_ICHECK(go.dtype() == dl_int32 && go.ndim() == 1 && go.stride(0) == 1 &&
+ go.size(0) > last_depth)
+ << "eagle_harness_chain: go flags";
+ TVM_FFI_ICHECK(sampled.dtype() == dl_bool && sampled.numel() >= 1)
+ << "eagle_harness_chain: sampled flag";
+ TVM_FFI_ICHECK(depth >= 1 && depth <= last_depth) << "eagle_harness_chain: depth";
+ chain_kernel<<<1, 1, 0, get_stream(execs.device())>>>(
+ static_cast<const int64_t*>(execs.data_ptr()), static_cast<const int32_t*>(go.data_ptr()),
+ static_cast<const bool*>(sampled.data_ptr()), static_cast<int>(depth),
+ static_cast<int>(last_depth));
+ check_cuda(cudaGetLastError(), "chain kernel launch");
+}
+
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(eagle_harness_chain_instantiate, eagle_harness_chain_instantiate);
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(eagle_harness_chain_destroy, eagle_harness_chain_destroy);
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(eagle_harness_chain_next, eagle_harness_chain_next);
diff --git a/eagle_harness/tokenspeed/tree_round/ops/csrc/eagle_harness_policy.cu b/eagle_harness/tokenspeed/tree_round/ops/csrc/eagle_harness_policy.cu
new file mode 100644
index 0000000..f618907
--- /dev/null
+++ b/eagle_harness/tokenspeed/tree_round/ops/csrc/eagle_harness_policy.cu
@@ -0,0 +1,1266 @@
+// Copyright 2026 Eagle AI Corp.
+// SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+#include <cub/block/block_scan.cuh>
+
+#include <climits>
+#include <cstdint>
+#include <functional>
+
+#include "tvm_ffi_utils.h"
+
+namespace {
+
+// Scalars of the int32 state tensor: the policy's persistent state, then the
+// current round's.
+enum State : int {
+ kTiny = 0, // is_tiny_batch_size
+ kTier, // the batch tier: 0 small, 1 medium, 2 large, 3 huge
+ kSampledNext, // sampled_depth_next
+ kSampledPlan, // sampled_depth_plan
+ kSampledSeen, // sampled_stop_seen (-1: None)
+ kBenchBatchSize, // exec mode 1's benchmark batch size (loaded before a round needs it)
+ kRankedCount, // cumulative ranked scores the next round sizes on (0: none)
+ kBatchSize, // the round's live requests (0: no round runs)
+ kSampled,
+ kCostId,
+ kInterval,
+ kVariant, // tree: tier at round start, or kTinyVariant; chain: tier row
+ kHistMax, // tree: the batch size's largest past verify width
+ kPastVerifyNum,
+ kLastDepth, // depth whose decision stopped the round
+ kStopWidth, // that decision's width
+ kCumuCount, // pool size after the round
+ kVerifyCount,
+ kFlat,
+ kVerifyNum,
+ kTableWidth, // chain: the width table's verify width of the round (0: the rule decides)
+ kNumState,
+};
+
+// Rows of the [4, depth + 1] slot tensor.
+enum SlotRow : int { kWidthRow = 0, kCumuStartRow, kWorkSizeRow, kGoRow, kNumSlotRows };
+
+constexpr int kTiers = 4;
+constexpr int kTinyVariant = kTiers; // cost variant (and verify floor) of a tiny round
+constexpr int kVariants = kTiers + 1;
+// tier_table: the verify floor per cost variant, then the width per tier.
+constexpr int kTierTableSize = kVariants + kTiers;
+constexpr int kMaxWidths = 32; // measured target widths per interval
+// A tree decision compares the work delta at its tier's width, min(K, 8 or 4).
+constexpr int kMaxNarrow = 8;
+// Verify history lengths (the reference keeps 16 past and 5 recent widths).
+constexpr int kMaxHistory = 32;
+// Tree depths whose cost row begin_round copies in one wave.
+constexpr int kMaxDepth = 32;
+
+// Columns of batch_table ([max_bs, cols], int64): begin_round's inputs per
+// batch size.
+// kTableWidthCol: a chain's width table width at the batch size (0: the rule decides).
+enum BatchCol : int {
+ kCostIdCol = 0,
+ kChainTierRowCol,
+ kIntervalsCol,
+ kCacheStepCol,
+ kTableWidthCol,
+ kBatchCols
+};
+// Columns of interval_i32 ([costs, intervals, cols], trees).
+enum IntervalI32Col : int { kNumWidthsCol = 0, kWidthsCol };
+// Columns of interval_f64: draft_cost[-1], model cost ratio, then the stop
+// thresholds per cost variant and depth, then the verify cost deltas.
+enum IntervalF64Col : int { kDraftCostCol = 0, kModelCostRatioCol, kStopThresholdCol };
+// Entries of chain_f64 ([costs, intervals, 2 tier rows, depth, entries]); the
+// cliff entries are 0 where no verify cost cliff makes the test look ahead.
+enum ChainF64 : int {
+ kGainDenom = 0,
+ kStepCost,
+ kChainThreshold,
+ kCliffGainDenom,
+ kCliffCost,
+ kChainF64
+};
+// The round's cost row, copied by begin_round: a tree's round_f64 holds the
+// draft cost, model cost ratio and the stop threshold per depth (of the
+// round's cost variant); a chain's its chain_f64 entries per depth (of the
+// round's tier row).
+enum RoundF64 : int { kRoundDraftCost = 0, kRoundModelCostRatio, kRoundThresholds };
+
+constexpr int kWarp = 32;
+constexpr unsigned kFullMask = 0xffffffffu;
+
+// torch.cumsum's CUB scan: 128 threads of 15 items per tile; two tiles keep
+// the decoupled look-back's sums in a fixed order.
+constexpr int kRankThreads = 128;
+constexpr int kRankItems = 15;
+constexpr int kRankTile = kRankThreads * kRankItems;
+constexpr int kRankTiles = 2;
+// The shapes whose torch.mean(dim=0) reduction order the ranking replicates.
+constexpr int kRankMaxRows = 32;
+constexpr int kChainMaxRows = 512;
+constexpr int kRankMaxCols = 64;
+
+using BlockScan = cub::BlockScan<float, kRankThreads, cub::BLOCK_SCAN_WARP_SCANS>;
+
+constexpr int ceil_div(int a, int b) { return (a + b - 1) / b; }
+
+// One lane or thread per entry: the one-warp kernels load a state scalar,
+// tier table entry and history entry per lane, verify_width_choose a width per
+// lane; select_verify's last two warps load the scores a verify compares.
+static_assert(kNumState <= kWarp && kTierTableSize <= kWarp && kMaxHistory <= kWarp);
+static_assert(kMaxNarrow < kWarp && kChainF64 <= kWarp && kMaxWidths <= kWarp);
+static_assert(kRankMaxCols <= kRankThreads - 2 * kWarp);
+// The ranked scores fit two scan tiles.
+static_assert(kRankMaxRows * kRankMaxCols <= kRankTile * kRankTiles);
+
+// Python's // on integers (floor), b != 0; 32-bit division when both fit.
+__device__ __forceinline__ int64_t floor_div(int64_t a, int64_t b) {
+ if (0 <= a && a <= UINT32_MAX && 0 < b && b <= UINT32_MAX) {
+ return static_cast<uint32_t>(a) / static_cast<uint32_t>(b);
+ }
+ int64_t q = a / b;
+ if (a % b != 0 && ((a < 0) != (b < 0))) --q;
+ return q;
+}
+
+// Up to kPerThread values per thread in registers: a kernel loads all its
+// inputs of a wave (load) before it stores any to shared memory (store), so
+// the loads overlap. Thread tid holds entries tid + k * threads, n <=
+// kPerThread * threads.
+template <int kPerThread, typename T>
+struct Fetch {
+ T v[kPerThread];
+
+ template <typename Src>
+ __device__ __forceinline__ void load(int n, int tid, int threads, Src src) {
+#pragma unroll
+ for (int k = 0; k < kPerThread; ++k) {
+ const int i = k * threads + tid;
+ if (i < n) v[k] = src(i);
+ }
+ }
+
+ __device__ __forceinline__ void store(T* dst, int n, int tid, int threads) const {
+#pragma unroll
+ for (int k = 0; k < kPerThread; ++k) {
+ const int i = k * threads + tid;
+ if (i < n) dst[i] = v[k];
+ }
+ }
+};
+
+// A width decision: the next depth's width and whether the cost criterion stops.
+struct Decision {
+ bool decided; // false: the decision compares work deltas
+ int width;
+ bool cost_stop;
+};
+
+// A round kernel's state and slots in shared memory: the slots of its depth
+// d (cur) and of depth d + 1 (next, written back at the end).
+struct RoundShared {
+ int32_t s[kNumState];
+ int32_t cur[kNumSlotRows];
+ int32_t next[kNumSlotRows];
+ int32_t tier_table[kTierTableSize];
+ int64_t seq;
+};
+
+// A tree round's past verify width (get_past_verify_num) at the current tiny and tier.
+__device__ __forceinline__ int tree_past_verify_num(const int32_t* s, const int32_t* tier_table) {
+ return max(s[kHistMax], tier_table[s[kTiny] ? kTinyVariant : s[kTier]]);
+}
+
+// Depth d's step of a round, on the shared copies (one thread).
+struct Round {
+ int32_t* s;
+ int32_t* cur;
+ int32_t* next;
+ int64_t* go_host; // [tree_depth + 1], mapped pinned memory
+ int64_t seq;
+ int depth;
+ int tree_depth;
+ int node_top_k;
+ bool chain;
+ const int32_t* tier_table; // trees
+ int verify_num;
+ int min_verify_count; // trees
+
+ // Whether depth d + 1 drafts, also to the host mirror: a relaxed
+ // system-scope store, unfenced, as the host reads nothing else on it.
+ __device__ void publish_go(bool draft) {
+ next[kGoRow] = draft;
+ const int64_t value = (seq << 1) | (draft ? 1 : 0);
+ *reinterpret_cast<volatile int64_t*>(go_host + depth + 1) = value;
+ }
+
+ // Whether depth d's slot asks for work deltas, which the next decision compares.
+ __device__ bool deltas_depth(int d) const {
+ if (chain) return d % 2 == 1 && d < tree_depth - 1;
+ if (s[kTiny] && d < 2) return false;
+ if (d == tree_depth - 1) return false;
+ return d % 2 == 0;
+ }
+
+ // Depth d's decision without work deltas ("narrow": the
+ // tree's width at the round's tier); not decided when it compares them.
+ __device__ Decision early_decision(int d, int narrow) const {
+ if (chain) {
+ if (d == tree_depth - 1) return {true, -1, true};
+ if (d == 0 || d % 2 == 1) return {true, 1, false};
+ return {false, 0, false};
+ }
+ if (d == tree_depth - 1) return {true, -1, true};
+ if (s[kTiny] && d < 2) return {true, node_top_k, false};
+ if (d % 2 == 0) return {true, narrow, false};
+ return {false, 0, false};
+ }
+
+ // The round stops after depth d (its children are the last in the pool);
+ // then complete_round (the start of _finalize): the ranked node count
+ // (verify_count) and whether the ranking is flat; a chain verifies every
+ // ranked node.
+ __device__ void finish(int decided_width) {
+ if (s[kSampled]) {
+ // Chains do not rank verify scores; complete their plan even at depth zero.
+ s[kSampledNext] = s[kSampledSeen] >= 0 ? s[kSampledSeen]
+ : min(s[kSampledPlan] + 2, tree_depth - 1);
+ }
+ s[kLastDepth] = depth;
+ s[kStopWidth] = decided_width;
+ s[kCumuCount] = cur[kCumuStartRow] + node_top_k * cur[kWidthRow];
+ publish_go(false);
+ if (chain) {
+ s[kVerifyCount] = min(s[kCumuCount], verify_num);
+ s[kVerifyNum] = s[kVerifyCount];
+ } else {
+ // past * 2 in int64: a cut round records a measured width up to 2**31 - 1.
+ const int64_t past = tree_past_verify_num(s, tier_table);
+ s[kVerifyCount] = static_cast<int>(
+ min(static_cast<int64_t>(min(verify_num, s[kCumuCount])),
+ max(past * 2, static_cast<int64_t>(min_verify_count))));
+ s[kFlat] = s[kTiny];
+ }
+ }
+
+ // Take depth d's decision: sampled rounds stop only at their planned depth
+ // (_sampled_round_stop); a continuing round writes depth d + 1's slots.
+ __device__ void commit(int decided_width, bool cost_stop) {
+ const int d = depth;
+ bool stop = cost_stop;
+ if (s[kSampled]) {
+ if (cost_stop && s[kSampledSeen] < 0) s[kSampledSeen] = d;
+ stop = d >= s[kSampledPlan];
+ }
+ if (stop) {
+ finish(decided_width);
+ return;
+ }
+ const int start = cur[kCumuStartRow] + node_top_k * cur[kWidthRow];
+ next[kWidthRow] = decided_width;
+ next[kCumuStartRow] = start;
+ next[kWorkSizeRow] = deltas_depth(d + 1) ? min(s[kPastVerifyNum], start) : 0;
+ publish_go(true);
+ }
+};
+
+// The loads of a decision kernel's one wave (one warp) are unconditional,
+// at indices clamped into range, so they issue back to back without
+// branches; the stores to shared memory follow them.
+struct RoundLoad {
+ int32_t state_value;
+ int32_t slot_value;
+ int64_t seq_value;
+
+ __device__ __forceinline__ void load(const int32_t* state, const int32_t* slots,
+ const int64_t* seq, int depth_slots, int d) {
+ const int lane = threadIdx.x;
+ state_value = state[min(lane, kNumState - 1)];
+ slot_value = slots[min(lane, kNumSlotRows - 1) * depth_slots + d];
+ seq_value = *seq;
+ }
+
+ __device__ __forceinline__ void store(RoundShared& sh) const {
+ const int lane = threadIdx.x;
+ if (lane < kNumState) sh.s[lane] = state_value;
+ if (lane < kNumSlotRows) {
+ sh.cur[lane] = slot_value;
+ sh.next[lane] = 0;
+ }
+ if (lane == 0) sh.seq = seq_value;
+ }
+};
+
+// The end of a decision kernel (one warp): the changed state scalars and
+// depth d + 1's slots back to global memory.
+__device__ __forceinline__ void store_round(const RoundShared& sh, int32_t* state,
+ int32_t state_value, int32_t* slots, int depth_slots,
+ int d) {
+ const int lane = threadIdx.x;
+ if (lane < kNumState && sh.s[lane] != state_value) state[lane] = sh.s[lane];
+ if (lane < kNumSlotRows) slots[lane * depth_slots + d + 1] = sh.next[lane];
+}
+
+// ---------------------------------------------------------------------------
+// Round start: past_verify_num and the cost
+// context's interval, depth 0's decision and depth 1's slots.
+// ---------------------------------------------------------------------------
+struct BeginInputs {
+ int bs;
+ bool sampled;
+ int64_t frontier_sum; // of the first bs cached lengths
+ const int64_t* batch_row; // batch_table's row of bs
+ int hist_max; // trees: the largest past verify width of bs
+ int chain_past_verify_num;
+};
+
+// A width table round of width W: depths 1..W-2 draft (the last drafted depth
+// W-2), and it verifies its whole pool of W nodes. Its stopping depth and width
+// are those the confidence rule records for a stop there.
+__device__ void begin_table_round(Round& r, int width) {
+ int32_t* s = r.s;
+ const int last = width - 2;
+ s[kTableWidth] = width;
+ s[kLastDepth] = last;
+ s[kStopWidth] = last == r.tree_depth - 1 ? -1 : 1;
+ s[kCumuCount] = width;
+ s[kVerifyCount] = min(width, r.verify_num);
+ s[kVerifyNum] = s[kVerifyCount];
+}
+
+// A width table round's slot of depth d (last: its last drafted depth): width
+// one from pool size d + 1, no work deltas, go up to the last drafted depth.
+// Depth 1 always runs (it begins the round), so a round stopping at depth 0
+// keeps a width-one depth 1 whose child no verify ranks.
+__device__ __forceinline__ int table_round_slot(int row, int d, int last) {
+ const bool runs = d <= max(last, 1);
+ if (row == kWidthRow) return runs ? 1 : 0;
+ if (row == kCumuStartRow) return runs ? d + 1 : 0;
+ if (row == kWorkSizeRow) return 0;
+ return d == 0 || d <= last;
+}
+
+__device__ void begin_round(Round& r, const int32_t* tier_table, const BeginInputs& in) {
+ int32_t* s = r.s;
+ for (int i = kBatchSize; i < kNumState; ++i) s[i] = 0;
+ const int bs = in.bs;
+ if (bs == 0) {
+ r.publish_go(false);
+ return;
+ }
+ s[kBatchSize] = bs;
+ s[kSampled] = in.sampled;
+ if (r.chain) {
+ s[kPastVerifyNum] = in.chain_past_verify_num;
+ const int table_width = static_cast<int>(in.batch_row[kTableWidthCol]);
+ if (table_width > 0) {
+ begin_table_round(r, table_width);
+ return;
+ }
+ } else {
+ s[kHistMax] = in.hist_max;
+ s[kPastVerifyNum] = tree_past_verify_num(s, tier_table);
+ }
+ if (in.sampled) {
+ // _begin_sampled_round
+ s[kSampledPlan] = s[kSampledNext];
+ s[kSampledSeen] = -1;
+ }
+ // The cost context's interval of the mean cached length (BatchCost.interval_index).
+ const int64_t* row = in.batch_row;
+ const int64_t step = row[kCacheStepCol];
+ s[kCostId] = static_cast<int>(row[kCostIdCol]);
+ const int64_t average_cache_len = floor_div(in.frontier_sum, bs);
+ // (average_cache_len - step) // step, exactly.
+ const int64_t interval =
+ min(max(floor_div(average_cache_len, step) - 1, static_cast<int64_t>(0)),
+ row[kIntervalsCol] - 1);
+ s[kInterval] = static_cast<int>(interval);
+ // Eager here, lazy in Python: tiny and tier change only after the first cost read.
+ s[kVariant] = r.chain ? static_cast<int>(row[kChainTierRowCol])
+ : (s[kTiny] ? kTinyVariant : s[kTier]);
+ // Depth 0: the root (one node) and its K children from the first step.
+ r.cur[kWidthRow] = 1;
+ r.cur[kCumuStartRow] = 1;
+ r.cur[kWorkSizeRow] = r.deltas_depth(0) ? 1 : 0;
+ r.cur[kGoRow] = 1;
+ // Depth 0's decision never compares work deltas: always decided early.
+ const Decision decision = r.early_decision(0, r.chain ? 1 : tier_table[kVariants + s[kTier]]);
+ r.commit(decision.width, decision.cost_stop);
+}
+
+// The cost table begin_round copies the round's row from: trees'
+// interval_f64, chains' chain_f64.
+struct CostTable {
+ const double* f64;
+ int num_intervals;
+ int cols; // trees
+};
+
+__global__ void __launch_bounds__(kWarp)
+ begin_round_kernel(int32_t* state, int32_t* slots, int64_t* go_host, int64_t* seq,
+ int tree_depth, int node_top_k, bool chain, const int32_t* hist,
+ int hist_len, const int64_t* batch_table, const int32_t* tier_table,
+ int tier_table_size, CostTable costs, double* round_f64,
+ const int32_t* live_rows, const int64_t* frontier, int64_t frontier_stride,
+ int64_t frontier_rows, const bool* sampled, int chain_past_verify_num,
+ int verify_num, int min_verify_count) {
+ __shared__ RoundShared sh;
+ __shared__ int64_t batch_row[kBatchCols];
+ __shared__ int32_t round_bs;
+ __shared__ bool round_sampled;
+ const int lane = threadIdx.x;
+ const int depth_slots = tree_depth + 1;
+ // Wave 1.
+ const int32_t state_value = lane < kNumState ? state[lane] : 0;
+ const int32_t tier_value = lane < tier_table_size ? tier_table[lane] : 0;
+ const int64_t seq_value = lane == 0 ? *seq : 0;
+ const int32_t bs_value = lane == 0 ? *live_rows : 0;
+ const bool sampled_value = lane == 0 ? *sampled : false;
+ if (lane < kNumState) sh.s[lane] = state_value;
+ if (lane < kNumSlotRows) {
+ sh.cur[lane] = 0;
+ sh.next[lane] = 0;
+ }
+ if (lane < kTierTableSize) sh.tier_table[lane] = tier_value;
+ if (lane == 0) {
+ sh.seq = seq_value;
+ round_bs = bs_value;
+ round_sampled = sampled_value;
+ }
+ __syncwarp();
+ // Wave 2: the batch size's table row, verify history and cached lengths.
+ const int bs = round_bs;
+ if (bs < 0 || bs > (chain ? kChainMaxRows : kRankMaxRows) || bs > frontier_rows) {
+ __trap();
+ return;
+ }
+ const bool load = bs > 0;
+ const int64_t* table_row = batch_table + static_cast<int64_t>(max(bs - 1, 0)) * kBatchCols;
+ const int32_t* history =
+ chain ? hist : hist + static_cast<int64_t>(max(bs - 1, 0)) * hist_len;
+ const int64_t batch_value = load && lane < kBatchCols ? __ldcg(table_row + lane) : 0;
+ const int32_t hist_value = load && lane < hist_len ? __ldcg(history + lane) : INT_MIN;
+ // Integer sums are exact in any order.
+ int64_t partial = 0;
+ if (load) {
+ constexpr int kPerLane = 8;
+ for (int base = 0; base < bs; base += kPerLane * kWarp) {
+ int64_t v[kPerLane];
+#pragma unroll
+ for (int k = 0; k < kPerLane; ++k) {
+ const int i = base + k * kWarp + lane;
+ v[k] = i < bs ? __ldcg(frontier + i * frontier_stride) : 0;
+ }
+#pragma unroll
+ for (int k = 0; k < kPerLane; ++k) partial += v[k];
+ }
+ }
+ for (int offset = kWarp / 2; offset > 0; offset /= 2) {
+ partial += __shfl_xor_sync(kFullMask, partial, offset);
+ }
+ const int hist_max = __reduce_max_sync(kFullMask, hist_value);
+ if (lane < kBatchCols) batch_row[lane] = batch_value;
+ __syncwarp();
+ if (lane == 0) {
+ // Idle warmups and discarded prefill chunks are not logical rounds.
+ Round r{sh.s, sh.cur, sh.next, go_host, sh.seq + (bs > 0), 0,
+ tree_depth, node_top_k, chain, sh.tier_table, verify_num, min_verify_count};
+ BeginInputs in{bs, round_sampled, partial, batch_row, hist_max, chain_past_verify_num};
+ begin_round(r, sh.tier_table, in);
+ *seq = r.seq;
+ sh.seq = r.seq;
+ }
+ __syncwarp();
+ const int table_width = sh.s[kTableWidth];
+ const int table_last = table_width - 2;
+ // A table round's go flags, up to the depth after its last drafted one
+ // (at least depth 2, which the drafter asks after depth 1).
+ if (table_width > 0) {
+ for (int d = lane + 1; d <= max(table_last + 1, 2); d += kWarp) {
+ const int64_t value = (sh.seq << 1) | (d <= table_last ? 1 : 0);
+ *reinterpret_cast<volatile int64_t*>(go_host + d) = value;
+ }
+ }
+ // Wave 3: the round's cost row, for its decisions (a table round takes none).
+ const int64_t row = static_cast<int64_t>(sh.s[kCostId]) * costs.num_intervals + sh.s[kInterval];
+ const int variant = sh.s[kVariant];
+ if (sh.s[kBatchSize] > 0 && table_width == 0) {
+ if (chain) {
+ const double* terms = costs.f64 + (row * 2 + variant) * tree_depth * kChainF64;
+ Fetch<ceil_div(kMaxDepth * kChainF64, kWarp), double> term_values;
+ term_values.load(tree_depth * kChainF64, lane, kWarp,
+ [=](int i) { return __ldcg(terms + i); });
+ term_values.store(round_f64, tree_depth * kChainF64, lane, kWarp);
+ } else {
+ const double* f64_row = costs.f64 + row * costs.cols;
+ const double* thresholds = f64_row + kStopThresholdCol + variant * tree_depth;
+ Fetch<ceil_div(kRoundThresholds + kMaxDepth, kWarp), double> values;
+ values.load(kRoundThresholds + tree_depth, lane, kWarp, [=](int i) {
+ return i < kRoundThresholds ? __ldcg(f64_row + kDraftCostCol + i)
+ : __ldcg(thresholds + i - kRoundThresholds);
+ });
+ values.store(round_f64, kRoundThresholds + tree_depth, lane, kWarp);
+ }
+ }
+ if (lane < kNumState && sh.s[lane] != state_value) state[lane] = sh.s[lane];
+ // Depths 0 and 1 from the round, the others cleared; a table round's every depth.
+ for (int row = 0; row < kNumSlotRows; ++row) {
+ for (int d = lane; d < depth_slots; d += kWarp) {
+ slots[row * depth_slots + d] = table_width > 0 ? table_round_slot(row, d, table_last)
+ : d == 0 ? sh.cur[row]
+ : d == 1 ? sh.next[row]
+ : 0;
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Depth d's decision (calculate_tree_width), before depth d drafts.
+// ---------------------------------------------------------------------------
+// row: draft_cost[-1], the model cost ratio and the stop threshold at the
+// decision's depth, from round_f64.
+__device__ void decide_tree(Round& r, const int32_t* tier_table, const float* work_deltas,
+ const double* row, int exec_mode, double async_layer_ratio) {
+ const int d = r.depth;
+ int32_t* s = r.s;
+ if (r.cur[kGoRow] != 1) {
+ r.publish_go(false);
+ return;
+ }
+ const int narrow = tier_table[kVariants + s[kTier]];
+ Decision decision = r.early_decision(d, narrow);
+ if (!decision.decided) {
+ const int bs = s[kBatchSize];
+ s[kTiny] = bs == 1;
+ // Preserve the caller's async ratio and one rounding per score operation.
+ double gain =
+ __dsub_rn(static_cast<double>(work_deltas[narrow]), static_cast<double>(work_deltas[0]));
+ gain = __ddiv_rn(gain, row[kRoundDraftCost]);
+ gain = __dmul_rn(gain, row[kRoundModelCostRatio]);
+ gain = __dmul_rn(gain, async_layer_ratio);
+ decision = {true, narrow, gain < row[kRoundThresholds]};
+ }
+ r.commit(decision.width, decision.cost_stop);
+}
+
+__global__ void __launch_bounds__(kWarp)
+ decide_tree_kernel(int32_t* state, int32_t* slots, int64_t* go_host, const int64_t* seq,
+ int tree_depth, int node_top_k, const float* work_deltas,
+ const double* round_f64, const int32_t* tier_table, int depth, int exec_mode,
+ double async_layer_ratio, int verify_num, int min_verify_count) {
+ __shared__ RoundShared sh;
+ __shared__ float deltas[kMaxNarrow + 1];
+ __shared__ double row[kRoundThresholds + 1];
+ const int lane = threadIdx.x;
+ const int d = depth;
+ const int depth_slots = tree_depth + 1;
+ // One wave: the round, the work deltas up to the widest compared one, and
+ // the cost row at depth d.
+ RoundLoad round;
+ round.load(state, slots, seq, depth_slots, d);
+ const int32_t tier_value = tier_table[min(lane, kTierTableSize - 1)];
+ const float delta_value = work_deltas[min(lane, min(node_top_k, kMaxNarrow))];
+ const double row_value = round_f64[lane < kRoundThresholds ? lane : kRoundThresholds + d];
+ round.store(sh);
+ if (lane < kTierTableSize) sh.tier_table[lane] = tier_value;
+ if (lane <= kMaxNarrow) deltas[lane] = delta_value;
+ if (lane <= kRoundThresholds) row[lane] = row_value;
+ __syncwarp();
+ // No live round (none begun, none requested, or a warm-up): nothing to decide.
+ if (sh.s[kBatchSize] <= 0) return;
+ if (lane == 0) {
+ Round r{sh.s, sh.cur, sh.next, go_host, sh.seq, d,
+ tree_depth, node_top_k, false, sh.tier_table, verify_num, min_verify_count};
+ decide_tree(r, sh.tier_table, deltas, row, exec_mode, async_layer_ratio);
+ }
+ __syncwarp();
+ store_round(sh, state, round.state_value, slots, depth_slots, d);
+}
+
+// Depth d's decision (calculate_chain_depth), before depth d drafts.
+__device__ void decide_chain(Round& r, const float* work_deltas, const double* terms) {
+ if (r.cur[kGoRow] != 1) {
+ r.publish_go(false);
+ return;
+ }
+ Decision decision = r.early_decision(r.depth, 1);
+ if (!decision.decided) {
+ // raw_gain * 2.0 / (1.0 + depth * depth_loss), against the step's cost
+ const double raw_gain = __dsub_rn(static_cast<double>(work_deltas[1]),
+ static_cast<double>(work_deltas[0]));
+ const double doubled = __dmul_rn(raw_gain, 2.0);
+ const double curr_gain = __ddiv_rn(doubled, terms[kGainDenom]);
+ bool stop = __ddiv_rn(curr_gain, terms[kStepCost]) < terms[kChainThreshold];
+ if (stop && terms[kCliffCost] != 0.0) {
+ // A verify cost cliff: look two depths ahead.
+ const double gain_two_steps =
+ __dadd_rn(curr_gain, __ddiv_rn(doubled, terms[kCliffGainDenom]));
+ stop = __ddiv_rn(gain_two_steps, terms[kCliffCost]) < terms[kChainThreshold];
+ }
+ decision = {true, 1, stop};
+ }
+ r.commit(decision.width, decision.cost_stop);
+}
+
+__global__ void __launch_bounds__(kWarp)
+ decide_chain_kernel(int32_t* state, int32_t* slots, int64_t* go_host, const int64_t* seq,
+ int tree_depth, const float* work_deltas, const double* round_f64,
+ int depth, int verify_num) {
+ __shared__ RoundShared sh;
+ __shared__ float deltas[2];
+ __shared__ double terms[kChainF64];
+ const int lane = threadIdx.x;
+ const int d = depth;
+ const int depth_slots = tree_depth + 1;
+ // One wave: the round, the work deltas and the stop test's terms at depth d.
+ RoundLoad round;
+ round.load(state, slots, seq, depth_slots, d);
+ const float delta_value = work_deltas[min(lane, 1)];
+ const double term_value = round_f64[d * kChainF64 + min(lane, kChainF64 - 1)];
+ round.store(sh);
+ if (lane < 2) deltas[lane] = delta_value;
+ if (lane < kChainF64) terms[lane] = term_value;
+ __syncwarp();
+ // No live round (none begun, none requested, or a warm-up): nothing to decide.
+ if (sh.s[kBatchSize] <= 0) return;
+ if (sh.s[kTableWidth] > 0) {
+ // begin_round wrote the width table round's slots and go flags; past its
+ // last drafted depth a decision only clears the next go flag, as a stopped
+ // round's does, and leaves the slots.
+ if (lane == 0 && sh.cur[kGoRow] != 1) {
+ *reinterpret_cast<volatile int64_t*>(go_host + d + 1) = sh.seq << 1;
+ }
+ return;
+ }
+ if (lane == 0) {
+ Round r{sh.s, sh.cur, sh.next, go_host, sh.seq, d, tree_depth, 1, true, nullptr, verify_num, 0};
+ decide_chain(r, deltas, terms);
+ }
+ __syncwarp();
+ store_round(sh, state, round.state_value, slots, depth_slots, d);
+}
+
+// ---------------------------------------------------------------------------
+// Cumulative ranked scores of top_scores[:rows, :cols], bit for bit as
+// torch.cumsum(top_scores.mean(dim=0), dim=0) (or of top_scores.view(-1)
+// when flat) on a contiguous tensor.
+// ---------------------------------------------------------------------------
+__device__ __forceinline__ int last_pow2(int n) {
+ int p = 1;
+ while (p * 2 <= n) p *= 2;
+ return p;
+}
+
+// torch's mean over dim 0 of a contiguous [rows, cols] float tensor
+// (Reduce.cuh with output vectorization, rows <= 32, cols <= 64): each thread
+// sums a column into 4 accumulators by row index mod 4 and combines them in
+// order; one column is instead split over last_pow2(rows) lanes, each summing
+// rows l and l + lanes, then reduced by halving offsets. The sum is scaled by
+// float(cols) / (rows * cols).
+__device__ float column_mean(const float* top, int stride, int rows, int cols, int c) {
+ const float factor = __fdiv_rn(static_cast<float>(cols), static_cast<float>(rows * cols));
+ float total;
+ if (cols == 1) {
+ float lanes[kRankMaxRows];
+ const int width = last_pow2(rows);
+ for (int l = 0; l < width; ++l) {
+ const float first = __fadd_rn(0.0f, top[l * stride]);
+ const float second = l + width < rows ? __fadd_rn(0.0f, top[(l + width) * stride]) : 0.0f;
+ lanes[l] = __fadd_rn(__fadd_rn(__fadd_rn(first, second), 0.0f), 0.0f);
+ }
+ for (int offset = width / 2; offset > 0; offset /= 2) {
+ for (int l = 0; l < offset; ++l) lanes[l] = __fadd_rn(lanes[l], lanes[l + offset]);
+ }
+ total = lanes[0];
+ } else {
+ float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f};
+ for (int k = 0; k < rows; ++k) acc[k % 4] = __fadd_rn(acc[k % 4], top[k * stride + c]);
+ total = __fadd_rn(__fadd_rn(__fadd_rn(acc[0], acc[1]), acc[2]), acc[3]);
+ }
+ return __fmul_rn(total, factor);
+}
+
+// The block prefix of the second tile: the first tile's aggregate, as CUB's
+// decoupled look-back hands it over.
+struct TilePrefix {
+ float prefix;
+ __device__ float operator()(float) const { return prefix; }
+};
+
+// Shared memory of the ranking: the [rows, cols] scores (row-major, zero to
+// the end of the second scan tile), turned in place into the cumulative
+// ranked scores.
+struct RankShared {
+ float values[kRankTile * kRankTiles];
+ float means[kRankMaxCols];
+ typename BlockScan::TempStorage scan;
+};
+
+// The ranked count of a [rows, cols] ranking: -1 outside the replicated shapes
+// or past the scores in memory (top_rows x top_cols) or the output capacity.
+__device__ int ranked_count(int rows, int cols, bool flat, int64_t top_rows, int64_t top_cols,
+ int64_t capacity) {
+ if (rows <= 0 || cols <= 0) return 0;
+ const int n = flat ? rows * cols : cols;
+ if (rows > kRankMaxRows || cols > kRankMaxCols || rows > top_rows || cols > top_cols ||
+ n > capacity) {
+ return -1;
+ }
+ return n;
+}
+
+// top[:rows, :cols] (rows of `stride` floats, a supported shape) loaded into
+// registers, then stored to rank.values with zeros past it; all
+// kRankThreads threads.
+struct ScoreFetch {
+ // Thread tid holds column tid % kRankMaxCols of rows tid / kRankMaxCols + k * kRowStep.
+ static constexpr int kRowStep = kRankThreads / kRankMaxCols;
+ static constexpr int kPerThread = kRankMaxRows / kRowStep;
+ float v[kPerThread];
+
+ __device__ __forceinline__ void load(const float* top, int64_t stride, int rows, int cols) {
+ const int col = threadIdx.x % kRankMaxCols;
+ const int row = threadIdx.x / kRankMaxCols;
+ const float* p = top + row * stride + col;
+#pragma unroll
+ for (int k = 0; k < kPerThread; ++k) {
+ if (col < cols && row + k * kRowStep < rows) v[k] = __ldcg(p);
+ p += kRowStep * stride;
+ }
+ }
+
+ __device__ __forceinline__ void store(RankShared& rank, int rows, int cols) const {
+ const int tid = threadIdx.x;
+ const int n = rows * cols;
+ const int col = tid % kRankMaxCols;
+ const int row = tid / kRankMaxCols;
+#pragma unroll
+ for (int k = 0; k < kPerThread; ++k) {
+ if (col < cols && row + k * kRowStep < rows) {
+ rank.values[(row + k * kRowStep) * cols + col] = v[k];
+ }
+ }
+ for (int i = n + (tid - n % kRankThreads + kRankThreads) % kRankThreads;
+ i < kRankTile * kRankTiles; i += kRankThreads) {
+ rank.values[i] = 0.0f;
+ }
+ }
+};
+
+// The cumulative ranked scores, in place in rank.values[0, ranked count); all
+// kRankThreads threads, after ScoreFetch::store and a barrier.
+__device__ void rank_scores(RankShared& rank, int rows, int cols, bool flat) {
+ const int tid = threadIdx.x;
+ if (!flat) {
+ if (tid < cols) rank.means[tid] = column_mean(rank.values, cols, rows, cols, tid);
+ __syncthreads();
+ for (int i = tid; i < rows * cols; i += kRankThreads) {
+ rank.values[i] = i < cols ? rank.means[i] : 0.0f;
+ }
+ __syncthreads();
+ }
+ const int n = flat ? rows * cols : cols;
+ float tile0_aggregate = 0.0f;
+ for (int tile = 0; tile < kRankTiles && tile * kRankTile < n; ++tile) {
+ const int base = tile * kRankTile + tid * kRankItems;
+ float items[kRankItems];
+ for (int i = 0; i < kRankItems; ++i) items[i] = rank.values[base + i];
+ if (tile == 0) {
+ // The (input, output, op, block_aggregate) overload: an output, not an initial value.
+ BlockScan(rank.scan).InclusiveScan(items, items, std::plus<float>(), tile0_aggregate);
+ } else {
+ TilePrefix prefix{tile0_aggregate};
+ BlockScan(rank.scan).InclusiveScan(items, items, std::plus<float>(), prefix);
+ }
+ __syncthreads();
+ for (int i = 0; i < kRankItems; ++i) rank.values[base + i] = items[i];
+ }
+ __syncthreads();
+}
+
+__global__ void __launch_bounds__(kRankThreads)
+ ranked_scores_kernel(const float* top, int64_t stride, int64_t top_rows, int64_t top_cols,
+ const int32_t* rows_ptr, const int32_t* cols_ptr, const int32_t* flat_ptr,
+ float* out, int32_t* out_count, int64_t capacity) {
+ __shared__ RankShared rank;
+ const int rows = *rows_ptr;
+ const int cols = *cols_ptr;
+ const bool flat = *flat_ptr != 0;
+ const int tid = threadIdx.x;
+ const int n = ranked_count(rows, cols, flat, top_rows, top_cols, capacity);
+ if (tid == 0) *out_count = n;
+ if (n <= 0) return;
+ ScoreFetch scores;
+ scores.load(top, stride, rows, cols);
+ scores.store(rank, rows, cols);
+ __syncthreads();
+ rank_scores(rank, rows, cols, flat);
+ for (int i = tid; i < n; i += kRankThreads) out[i] = rank.values[i];
+}
+
+// ---------------------------------------------------------------------------
+// Verify width (calculate_verify_nums_paged), the
+// verify history and this round's ranked scores published
+// for the next round.
+// ---------------------------------------------------------------------------
+__device__ int find_majority(const int32_t* nums, int n) {
+ for (int i = 0; i < n; ++i) {
+ int count = 0;
+ for (int j = 0; j < n; ++j) count += nums[j] == nums[i];
+ if (count > n / 2) return nums[i];
+ }
+ return -1;
+}
+
+__device__ void shift_in(int32_t* nums, int n, int value) {
+ for (int i = 0; i + 1 < n; ++i) nums[i] = nums[i + 1];
+ nums[n - 1] = value;
+}
+
+// A round's verify inputs: its (batch size, interval) row of the verify
+// tables and its (cost data, interval) row of the interval tables.
+struct VerifyRow {
+ int32_t tier; // _cost_tier
+ double thresholds[2]; // threshold * 0.95, * 1.05
+ int32_t num_widths;
+ int32_t index[kMaxWidths]; // measured target widths
+ // The verify width's cost deltas by position ([max_widths, max_widths]); 0
+ // where cost_delta > 0.04 fails.
+ double cost_delta[kMaxWidths * kMaxWidths];
+};
+
+// The verify width's state between its serial steps and its score comparisons.
+struct VerifyPlan {
+ bool compare; // the width needs the score comparisons
+ int width; // otherwise
+ int n; // measured widths below the ranked count
+ int widths[kMaxWidths];
+ int last_verify_num;
+ const float* ranked; // the ranked scores it sizes on (shared memory)
+ // Per position pair (i, j) and stability threshold: whether width j's
+ // gain per cost over width i falls below it.
+ bool below[kMaxWidths * kMaxWidths * 2];
+};
+
+// verify_width_unranked: the largest measured width below the ranked count.
+__device__ int verify_width_unranked(int32_t* recent, int recent_len, const VerifyRow& v,
+ int verify_count) {
+ int best = -1;
+ for (int i = 0; i < v.num_widths; ++i) {
+ const int w = v.index[i];
+ if (w < verify_count) best = max(best, w);
+ }
+ const int width = best >= 0 ? best + 1 : 1;
+ shift_in(recent, recent_len, width);
+ return width;
+}
+
+// The verify width on cumulative ranked scores (fp32, widened exactly), up to the
+// score comparisons: sets plan.width, or plan.compare and their inputs.
+// Width 1 is a measured width (and exec mode 1 measures a second one).
+__device__ void verify_width_plan(const int32_t* s, int32_t* recent, int recent_len,
+ const VerifyRow& v, int exec_mode, int verify_count,
+ const float* ranked, int ranked_len, VerifyPlan& plan) {
+ plan.compare = false;
+ plan.width = 0;
+ plan.last_verify_num = find_majority(recent, recent_len);
+ shift_in(recent, recent_len, verify_count);
+ const int num_widths = v.num_widths;
+ const int32_t* index = v.index;
+ const int limit = min(ranked_len, verify_count);
+ int n = 0;
+ int largest = 0;
+ for (int i = 0; i < num_widths; ++i) {
+ if (index[i] < limit) {
+ plan.widths[n++] = index[i];
+ largest = max(largest, index[i]);
+ }
+ }
+ if (largest == 0) {
+ recent[recent_len - 1] = 1;
+ plan.width = 1;
+ return;
+ }
+ plan.compare = true;
+ plan.n = n;
+ plan.ranked = ranked;
+}
+
+// The score comparisons, both stability thresholds of every position pair at
+// once (all threads): the same operations as the serial loop, off its chain.
+__device__ void verify_width_compare(const VerifyRow& v, int max_widths, VerifyPlan& plan) {
+ const int n = plan.n;
+ for (int p = threadIdx.x; p < n * n * 2; p += kRankThreads) {
+ const int stable = p % 2;
+ const int i = p / 2 / n;
+ const int j = p / 2 % n;
+ bool below = false;
+ if (i < j) {
+ const double delta = v.cost_delta[i * max_widths + j];
+ below = delta > 0.0 && __ddiv_rn(__dsub_rn(static_cast<double>(plan.ranked[plan.widths[j]]),
+ static_cast<double>(plan.ranked[plan.widths[i]])),
+ delta) < v.thresholds[stable];
+ }
+ plan.below[p] = below;
+ }
+}
+
+// The verify width after the comparisons (warp 0): the stability mask and the
+// chosen width. Each width's mask entry changes only in its own column of
+// the pair loop, so lane j replays column j in order.
+__device__ int verify_width_choose(int32_t* recent, int recent_len, int verify_count,
+ const VerifyPlan& plan) {
+ const int lane = threadIdx.x;
+ const int n = plan.n;
+ int mask = INT_MIN;
+ int smallest = INT_MAX; // over widths[1:]
+ if (lane < n) {
+ mask = plan.widths[lane];
+ const int reset = plan.widths[1];
+ for (int i = 0; i < lane; ++i) {
+ const int stable = plan.last_verify_num <= mask + 1 ? 0 : 1;
+ if (plan.below[(i * n + lane) * 2 + stable]) mask = reset;
+ }
+ if (lane >= 1) smallest = plan.widths[lane];
+ }
+ int chosen = __reduce_max_sync(kFullMask, mask) + 1;
+ smallest = __reduce_min_sync(kFullMask, smallest);
+ if (lane == 0) recent[recent_len - 1] = chosen;
+ if (chosen == 1 || verify_count < chosen) chosen = smallest + 1;
+ return chosen;
+}
+
+struct VerifyTables {
+ const int32_t* interval_i32; // widths from kNumWidthsCol
+ const double* interval_f64; // cost deltas from cost_delta_col
+ const int32_t* verify_i32; // [max_bs, intervals]: tier
+ const double* verify_f64; // [max_bs, intervals, 2]: threshold * 0.95, * 1.05
+ int num_intervals;
+ int interval_i32_cols;
+ int interval_f64_cols;
+ int cost_delta_col; // of the [max_widths, max_widths] cost deltas
+ int max_widths;
+};
+
+// This round's ranked scores and verify width: the scores are published for
+// the next round before the verify is sized, which reads the previous round's
+// (its own in the first).
+__global__ void __launch_bounds__(kRankThreads)
+ select_verify_kernel(int32_t* state, int32_t* recent, int recent_len, int32_t* hist,
+ int hist_len, float* published, int64_t published_capacity,
+ const float* top, int64_t top_stride, int64_t top_rows, int64_t top_cols,
+ VerifyTables tables, int tree_depth, int exec_mode) {
+ __shared__ int32_t s[kNumState];
+ __shared__ int32_t recent_sh[kMaxHistory];
+ __shared__ int32_t hist_row[kMaxHistory];
+ __shared__ float previous[kRankMaxCols]; // the published scores a verify reads
+ __shared__ RankShared rank;
+ __shared__ VerifyRow v;
+ __shared__ VerifyPlan plan;
+ const int tid = threadIdx.x;
+ // Wave 1. The verify compares scores below verify_count <= kRankMaxCols.
+ const int32_t state_value = tid < kNumState ? state[tid] : 0;
+ const int recent_tid = tid - kWarp;
+ const int32_t recent_value = 0 <= recent_tid && recent_tid < recent_len ? recent[recent_tid] : 0;
+ const int previous_tid = tid - 2 * kWarp;
+ const float previous_value =
+ 0 <= previous_tid &&
+ previous_tid < min(static_cast<int64_t>(kRankMaxCols), published_capacity)
+ ? published[previous_tid]
+ : 0.0f;
+ if (tid < kNumState) s[tid] = state_value;
+ if (0 <= recent_tid && recent_tid < recent_len) recent_sh[recent_tid] = recent_value;
+ if (0 <= previous_tid && previous_tid < kRankMaxCols) previous[previous_tid] = previous_value;
+ __syncthreads();
+ const int bs = s[kBatchSize];
+ if (bs <= 0) return;
+ const int rows = bs;
+ const int verify_count = s[kVerifyCount];
+ const bool flat = s[kFlat] != 0;
+ const int own_count =
+ ranked_count(rows, verify_count, flat, top_rows, top_cols, published_capacity);
+ if (own_count <= 0) {
+ __trap();
+ return;
+ }
+ // Wave 2: the scores, the verify history and the verify inputs, all loaded
+ // before any is stored.
+ ScoreFetch scores;
+ scores.load(top, top_stride, rows, verify_count);
+ int32_t* history = hist + static_cast<int64_t>(bs - 1) * hist_len;
+ const int64_t verify_row = static_cast<int64_t>(bs - 1) * tables.num_intervals + s[kInterval];
+ const int64_t interval_row =
+ static_cast<int64_t>(s[kCostId]) * tables.num_intervals + s[kInterval];
+ const int32_t* widths_row = tables.interval_i32 + interval_row * tables.interval_i32_cols;
+ const double* deltas_row =
+ tables.interval_f64 + interval_row * tables.interval_f64_cols + tables.cost_delta_col;
+ const int max_widths = tables.max_widths;
+ const int32_t hist_value = tid < hist_len ? __ldcg(history + tid) : 0;
+ const int32_t index_value = tid < max_widths ? __ldcg(widths_row + kWidthsCol + tid) : 0;
+ const int32_t i32_value = tid == 0 ? __ldcg(tables.verify_i32 + verify_row)
+ : tid == 1 ? __ldcg(widths_row + kNumWidthsCol)
+ : 0;
+ const double f64_value = tid < 2 ? __ldcg(tables.verify_f64 + verify_row * 2 + tid) : 0.0;
+ Fetch<ceil_div(kMaxWidths * kMaxWidths, kRankThreads), double> deltas;
+ deltas.load(max_widths * max_widths, tid, kRankThreads,
+ [=](int i) { return __ldcg(deltas_row + i); });
+ scores.store(rank, rows, verify_count);
+ if (tid < hist_len) hist_row[tid] = hist_value;
+ if (tid < max_widths) v.index[tid] = index_value;
+ if (tid == 0) v.tier = i32_value;
+ if (tid == 1) v.num_widths = i32_value;
+ if (tid < 2) v.thresholds[tid] = f64_value;
+ deltas.store(v.cost_delta, max_widths * max_widths, tid, kRankThreads);
+ __syncthreads();
+ rank_scores(rank, rows, verify_count, flat);
+ for (int i = tid; i < own_count; i += kRankThreads) published[i] = rank.values[i];
+ if (tid == 0) {
+ // eagle_harness_verify_cost_context sets the tier.
+ s[kTier] = v.tier;
+ const int previous_count = s[kRankedCount];
+ plan.compare = false;
+ plan.width = 0;
+ if (previous_count > 0) {
+ verify_width_plan(s, recent_sh, recent_len, v, exec_mode, verify_count, previous,
+ previous_count, plan);
+ } else if (s[kSampled]) {
+ // Current sampled proposals cannot choose their own verify budget.
+ plan.width = verify_width_unranked(recent_sh, recent_len, v, verify_count);
+ } else {
+ // The first round decides on its own scores.
+ verify_width_plan(s, recent_sh, recent_len, v, exec_mode, verify_count, rank.values,
+ own_count, plan);
+ }
+ }
+ __syncthreads();
+ int width = plan.width;
+ if (plan.compare) {
+ verify_width_compare(v, max_widths, plan);
+ __syncthreads();
+ if (tid < kWarp) width = verify_width_choose(recent_sh, recent_len, verify_count, plan);
+ }
+ if (tid == 0) {
+ s[kVerifyNum] = width;
+ // put_past_verify_num shifts the history in the write-back below.
+ s[kRankedCount] = own_count;
+ }
+ __syncthreads();
+ if (tid < kNumState && s[tid] != state_value) state[tid] = s[tid];
+ if (0 <= recent_tid && recent_tid < recent_len && recent_sh[recent_tid] != recent_value) {
+ recent[recent_tid] = recent_sh[recent_tid];
+ }
+ // put_past_verify_num: the history shifted by one, the width last.
+ if (tid < hist_len) {
+ history[tid] = tid + 1 < hist_len ? hist_row[tid + 1] : s[kVerifyNum];
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Host entry points
+// ---------------------------------------------------------------------------
+// The checks below cover what the kernels index past their fixed capacities
+// or read through a caller's view; device_policy.py builds every table,
+// state and slot tensor contiguous in the kernels' dtypes and layouts.
+
+// tree_depth from the [4, tree_depth + 1] slots, within kMaxDepth.
+int round_depth(const TensorView& slots) {
+ TVM_FFI_ICHECK(slots.ndim() == 2 && slots.size(0) == 4 && slots.IsContiguous());
+ TVM_FFI_ICHECK(slots.size(1) >= 3 && slots.size(1) - 1 <= kMaxDepth)
+ << "eagle_harness_policy: tree depth past " << kMaxDepth;
+ return static_cast<int>(slots.size(1)) - 1;
+}
+
+void check_round(const TensorView& state, const TensorView& slots, const TensorView& seq,
+ const TensorView& go_host) {
+ check_tensor(state, dl_int32, state.device());
+ check_tensor(slots, dl_int32, state.device());
+ check_scalar(seq, dl_int64, state.device());
+ TVM_FFI_ICHECK(state.IsContiguous() && state.numel() == kNumState);
+ TVM_FFI_ICHECK(go_host.device().device_type == kDLCPU && go_host.dtype() == dl_int64 &&
+ go_host.IsContiguous() && go_host.numel() == slots.size(1));
+ // go_host is mapped pinned memory allocated by DevicePolicy.
+}
+
+// A decision's depth and its work deltas: contiguous [n].
+void check_decision(int64_t depth, int tree_depth, const TensorView& work_deltas, int64_t n) {
+ TVM_FFI_ICHECK(depth >= 1 && depth < tree_depth) << "eagle_harness_policy: decision depth";
+ TVM_FFI_ICHECK(work_deltas.ndim() == 1 && work_deltas.size(0) == n && work_deltas.stride(0) == 1)
+ << "eagle_harness_policy: work deltas must be contiguous [" << n << "]";
+}
+
+} // namespace
+
+void eagle_harness_policy_begin_round(TensorView state, TensorView seq, TensorView hist,
+ TensorView slots, TensorView go_host, TensorView batch_table,
+ TensorView tier_table, TensorView cost_f64,
+ TensorView round_f64, TensorView live_rows,
+ TensorView frontier, TensorView sampled, bool chain,
+ int64_t node_top_k, int64_t chain_past_verify_num,
+ int64_t verify_num, int64_t min_verify_count) {
+ const int tree_depth = round_depth(slots);
+ check_round(state, slots, seq, go_host);
+ check_scalar(live_rows, dl_int32, state.device());
+ check_scalar(sampled, dl_bool, state.device());
+ check_tensor(frontier, dl_int64, state.device());
+ TVM_FFI_ICHECK(frontier.ndim() == 1);
+ for (const TensorView* t : {&hist, &tier_table}) {
+ check_tensor(*t, dl_int32, state.device());
+ TVM_FFI_ICHECK(t->IsContiguous());
+ }
+ for (const TensorView* t : {&cost_f64, &round_f64}) {
+ check_tensor(*t, dl_float64, state.device());
+ TVM_FFI_ICHECK(t->IsContiguous());
+ }
+ check_tensor(batch_table, dl_int64, state.device());
+ const int max_bs = chain ? kChainMaxRows : kRankMaxRows;
+ TVM_FFI_ICHECK(batch_table.IsContiguous() && batch_table.ndim() == 2 &&
+ batch_table.size(0) == max_bs && batch_table.size(1) == kBatchCols &&
+ hist.ndim() == 2 && hist.size(0) == max_bs && tier_table.ndim() == 1 &&
+ round_f64.ndim() == 1);
+ if (chain) {
+ TVM_FFI_ICHECK(node_top_k == 1 && tree_depth <= 15 &&
+ verify_num >= 2 && verify_num <= 16 && chain_past_verify_num == 16)
+ << "Unsupported chain shape";
+ TVM_FFI_ICHECK(hist.size(1) == 0 && tier_table.numel() == 0 &&
+ round_f64.numel() == tree_depth * kChainF64 &&
+ cost_f64.ndim() == 5 && cost_f64.size(0) == kChainMaxRows &&
+ cost_f64.size(1) > 0 && cost_f64.size(2) == 2 &&
+ cost_f64.size(3) == tree_depth && cost_f64.size(4) == kChainF64);
+ } else {
+ TVM_FFI_ICHECK(chain_past_verify_num == 0 &&
+ (node_top_k == 2 || node_top_k == 4 || node_top_k == 8) &&
+ (tree_depth - 1) * node_top_k <= 64 && verify_num >= 2 && verify_num <= 64)
+ << "Unsupported tree shape";
+ TVM_FFI_ICHECK(hist.size(1) > 0 && tier_table.numel() == kTierTableSize &&
+ round_f64.numel() == 2 + tree_depth && cost_f64.ndim() == 3 &&
+ cost_f64.size(0) > 0 && cost_f64.size(1) > 0 &&
+ cost_f64.size(2) >= kStopThresholdCol + kVariants * tree_depth);
+ }
+ TVM_FFI_ICHECK_LE(hist.size(1), kMaxHistory) << "eagle_harness_policy: verify history";
+ CostTable costs;
+ costs.f64 = static_cast<const double*>(cost_f64.data_ptr());
+ costs.num_intervals = static_cast<int>(cost_f64.size(1));
+ costs.cols = chain ? 0 : static_cast<int>(cost_f64.size(2));
+ begin_round_kernel<<<1, kWarp, 0, get_stream(state.device())>>>(
+ static_cast<int32_t*>(state.data_ptr()), static_cast<int32_t*>(slots.data_ptr()),
+ static_cast<int64_t*>(go_host.data_ptr()), static_cast<int64_t*>(seq.data_ptr()), tree_depth,
+ static_cast<int>(node_top_k), chain, static_cast<const int32_t*>(hist.data_ptr()),
+ static_cast<int>(hist.size(1)), static_cast<const int64_t*>(batch_table.data_ptr()),
+ static_cast<const int32_t*>(tier_table.data_ptr()), static_cast<int>(tier_table.size(0)),
+ costs, static_cast<double*>(round_f64.data_ptr()),
+ static_cast<const int32_t*>(live_rows.data_ptr()),
+ static_cast<const int64_t*>(frontier.data_ptr()), frontier.stride(0), frontier.size(0),
+ static_cast<const bool*>(sampled.data_ptr()), static_cast<int>(chain_past_verify_num),
+ static_cast<int>(verify_num), static_cast<int>(min_verify_count));
+}
+
+void eagle_harness_policy_decide_tree(TensorView state, TensorView seq, TensorView slots,
+ TensorView go_host, TensorView work_deltas,
+ TensorView round_f64, TensorView tier_table, int64_t depth,
+ int64_t node_top_k, int64_t exec_mode,
+ double async_layer_ratio, int64_t verify_num,
+ int64_t min_verify_count) {
+ const int tree_depth = round_depth(slots);
+ TVM_FFI_ICHECK(exec_mode == 0) << "Only serving policy is supported";
+ check_round(state, slots, seq, go_host);
+ check_tensor(work_deltas, dl_float32, state.device());
+ check_tensor(round_f64, dl_float64, state.device());
+ check_tensor(tier_table, dl_int32, state.device());
+ TVM_FFI_ICHECK(round_f64.IsContiguous() && round_f64.numel() == 2 + tree_depth &&
+ tier_table.IsContiguous() && tier_table.numel() == kTierTableSize);
+ check_decision(depth, tree_depth, work_deltas, node_top_k + 1);
+ decide_tree_kernel<<<1, kWarp, 0, get_stream(state.device())>>>(
+ static_cast<int32_t*>(state.data_ptr()), static_cast<int32_t*>(slots.data_ptr()),
+ static_cast<int64_t*>(go_host.data_ptr()), static_cast<const int64_t*>(seq.data_ptr()),
+ tree_depth, static_cast<int>(node_top_k), static_cast<const float*>(work_deltas.data_ptr()),
+ static_cast<const double*>(round_f64.data_ptr()),
+ static_cast<const int32_t*>(tier_table.data_ptr()), static_cast<int>(depth),
+ static_cast<int>(exec_mode), async_layer_ratio, static_cast<int>(verify_num),
+ static_cast<int>(min_verify_count));
+}
+
+void eagle_harness_policy_decide_chain(TensorView state, TensorView seq, TensorView slots,
+ TensorView go_host, TensorView work_deltas,
+ TensorView round_f64, int64_t depth, int64_t verify_num) {
+ const int tree_depth = round_depth(slots);
+ check_round(state, slots, seq, go_host);
+ check_tensor(work_deltas, dl_float32, state.device());
+ check_tensor(round_f64, dl_float64, state.device());
+ TVM_FFI_ICHECK(tree_depth <= 15 && verify_num >= 2 && verify_num <= 16 &&
+ round_f64.IsContiguous() && round_f64.numel() == tree_depth * kChainF64);
+ check_decision(depth, tree_depth, work_deltas, 2);
+ decide_chain_kernel<<<1, kWarp, 0, get_stream(state.device())>>>(
+ static_cast<int32_t*>(state.data_ptr()), static_cast<int32_t*>(slots.data_ptr()),
+ static_cast<int64_t*>(go_host.data_ptr()), static_cast<const int64_t*>(seq.data_ptr()),
+ tree_depth, static_cast<const float*>(work_deltas.data_ptr()),
+ static_cast<const double*>(round_f64.data_ptr()), static_cast<int>(depth),
+ static_cast<int>(verify_num));
+}
+
+void eagle_harness_ranked_scores(TensorView top_scores, TensorView rows, TensorView cols,
+ TensorView flat, TensorView out, TensorView out_count) {
+ check_tensor(top_scores, dl_float32, top_scores.device());
+ check_tensor(out, dl_float32, top_scores.device());
+ for (const TensorView* t : {&rows, &cols, &flat, &out_count})
+ check_scalar(*t, dl_int32, top_scores.device());
+ TVM_FFI_ICHECK(out.ndim() == 1 && out.IsContiguous());
+ TVM_FFI_ICHECK(top_scores.ndim() == 2 && top_scores.stride(1) == 1)
+ << "eagle_harness_policy: top scores must have unit column stride";
+ ranked_scores_kernel<<<1, kRankThreads, 0, get_stream(top_scores.device())>>>(
+ static_cast<const float*>(top_scores.data_ptr()), top_scores.stride(0), top_scores.size(0),
+ top_scores.size(1), static_cast<const int32_t*>(rows.data_ptr()),
+ static_cast<const int32_t*>(cols.data_ptr()), static_cast<const int32_t*>(flat.data_ptr()),
+ static_cast<float*>(out.data_ptr()), static_cast<int32_t*>(out_count.data_ptr()),
+ out.size(0));
+}
+
+void eagle_harness_policy_select_verify(TensorView state, TensorView recent, TensorView hist,
+ TensorView published, TensorView top_scores,
+ TensorView interval_i32, TensorView interval_f64,
+ TensorView verify_i32, TensorView verify_f64,
+ int64_t tree_depth, int64_t exec_mode) {
+ TVM_FFI_ICHECK(exec_mode == 0) << "Only serving policy is supported";
+ for (const TensorView* t : {&state, &recent, &hist, &interval_i32, &verify_i32}) {
+ check_tensor(*t, dl_int32, state.device());
+ TVM_FFI_ICHECK(t->IsContiguous());
+ }
+ for (const TensorView* t : {&interval_f64, &verify_f64}) {
+ check_tensor(*t, dl_float64, state.device());
+ TVM_FFI_ICHECK(t->IsContiguous());
+ }
+ check_tensor(published, dl_float32, state.device());
+ check_tensor(top_scores, dl_float32, state.device());
+ TVM_FFI_ICHECK(state.numel() == kNumState && published.IsContiguous() && top_scores.ndim() == 2 &&
+ hist.ndim() == 2 && hist.size(1) > 0 && recent.numel() > 0);
+ TVM_FFI_ICHECK(hist.size(1) <= kMaxHistory && recent.size(0) <= kMaxHistory)
+ << "eagle_harness_policy: verify history";
+ // Live rows up to the batch, verify counts up to the columns.
+ TVM_FFI_ICHECK(hist.size(0) <= kRankMaxRows && top_scores.size(1) <= kRankMaxCols &&
+ top_scores.stride(1) == 1)
+ << "eagle_harness_policy: ranked scores past the replicated torch shapes";
+ VerifyTables tables;
+ tables.max_widths = static_cast<int>(interval_i32.size(2)) - kWidthsCol;
+ tables.cost_delta_col = kStopThresholdCol + kVariants * static_cast<int>(tree_depth);
+ TVM_FFI_ICHECK_LE(tables.max_widths, kMaxWidths) << "eagle_harness_policy: measured widths";
+ tables.interval_i32 = static_cast<const int32_t*>(interval_i32.data_ptr());
+ tables.interval_f64 = static_cast<const double*>(interval_f64.data_ptr());
+ tables.verify_i32 = static_cast<const int32_t*>(verify_i32.data_ptr());
+ tables.verify_f64 = static_cast<const double*>(verify_f64.data_ptr());
+ tables.num_intervals = static_cast<int>(interval_i32.size(1));
+ tables.interval_i32_cols = static_cast<int>(interval_i32.size(2));
+ tables.interval_f64_cols = static_cast<int>(interval_f64.size(2));
+ select_verify_kernel<<<1, kRankThreads, 0, get_stream(state.device())>>>(
+ static_cast<int32_t*>(state.data_ptr()), static_cast<int32_t*>(recent.data_ptr()),
+ static_cast<int>(recent.size(0)), static_cast<int32_t*>(hist.data_ptr()),
+ static_cast<int>(hist.size(1)), static_cast<float*>(published.data_ptr()), published.size(0),
+ static_cast<const float*>(top_scores.data_ptr()), top_scores.stride(0), top_scores.size(0),
+ top_scores.size(1), tables, static_cast<int>(tree_depth), static_cast<int>(exec_mode));
+}
+
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(eagle_harness_policy_begin_round, eagle_harness_policy_begin_round);
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(eagle_harness_policy_decide_tree, eagle_harness_policy_decide_tree);
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(eagle_harness_policy_decide_chain, eagle_harness_policy_decide_chain);
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(eagle_harness_ranked_scores, eagle_harness_ranked_scores);
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(eagle_harness_policy_select_verify,
+ eagle_harness_policy_select_verify);
diff --git a/eagle_harness/tokenspeed/tree_round/ops/csrc/eagle_harness_rejection.cu b/eagle_harness/tokenspeed/tree_round/ops/csrc/eagle_harness_rejection.cu
new file mode 100644
index 0000000..dbf00f5
--- /dev/null
+++ b/eagle_harness/tokenspeed/tree_round/ops/csrc/eagle_harness_rejection.cu
@@ -0,0 +1,402 @@
+// Copyright 2026 Eagle AI Corp.
+// SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+// Recursive tree rejection sampling and its residual bonus token.
+
+#include <algorithm>
+#include <atomic>
+#include <climits>
+#include <cstdint>
+
+#include "tvm_ffi_utils.h"
+
+using tvm::ffi::Optional;
+
+constexpr int MAX_TREE_NODES = 64;
+
+// Verify ranking order, torch.argmax's: NaN first, then larger value, then lower index.
+__device__ __forceinline__ bool argmax_before(float v, int i, float best_v, int best_i) {
+ const bool an = isnan(v);
+ const bool bn = isnan(best_v);
+ if (an != bn) return an;
+ if (!an && v != best_v) return v > best_v;
+ return i < best_i;
+}
+
+// Tree rejection sampling, one CTA per request, one warp per node; greedy rows use the argmax only.
+__device__ __forceinline__ int next_child(const int32_t* s_parent, int node, int after,
+ int num_nodes) {
+ for (int j = after + 1; j < num_nodes; ++j) {
+ if (s_parent[j] == node) return j;
+ }
+ return -1;
+}
+
+__global__ void tree_reject_sample_kernel(
+ float* __restrict__ probas, int64_t probas_stride, const int32_t* __restrict__ tokens,
+ const int32_t* __restrict__ parents, const int64_t* __restrict__ q_rows,
+ const int32_t* __restrict__ q_slot, const int32_t* __restrict__ q_pos,
+ const float* __restrict__ q_store, const int32_t* __restrict__ qid_store,
+ const float* __restrict__ coins, int64_t coins_stride, const int32_t* __restrict__ top_ks,
+ const int64_t* __restrict__ argmax, int32_t* __restrict__ path,
+ int32_t* __restrict__ predicts, int32_t* __restrict__ accept_length,
+ int64_t* __restrict__ last_row, int num_nodes, int num_slots, int nc, int vocab) {
+ const int b = blockIdx.x;
+ __shared__ int32_t s_parent[MAX_TREE_NODES];
+ __shared__ int s_accept_child[MAX_TREE_NODES];
+ for (int i = threadIdx.x; i < num_nodes; i += blockDim.x) {
+ s_parent[i] = parents[(int64_t)b * num_nodes + i];
+ }
+ __syncthreads();
+ const int lane = threadIdx.x & 31;
+ const int num_warps = blockDim.x >> 5;
+ const int64_t q_row = q_rows != nullptr ? q_rows[b] : -1;
+ for (int node = threadIdx.x >> 5; node < num_nodes; node += num_warps) {
+ const int64_t row = (int64_t)b * num_nodes + node;
+ float* p = probas + row * probas_stride;
+ int child = next_child(s_parent, node, node, num_nodes);
+ int accepted = -1;
+ const bool greedy = top_ks[row] == 1;
+ const int32_t slot =
+ (!greedy && q_row >= 0 && child >= 0) ? q_slot[q_row * num_nodes + child] : -1;
+ if (slot >= 0) {
+ const int64_t store_row = (q_row * num_slots + slot) * nc;
+ const float* q_row_ptr = q_store + store_row;
+ const int32_t* id_row = qid_store + store_row;
+ constexpr int MAX_SAMPLED_CHILDREN = 16;
+ int rejected_pos[MAX_SAMPLED_CHILDREN];
+ int rejected_count = 0;
+ float q_left = 0.0f, p_cand = 0.0f;
+ // Argmax before the updates, for a vanishing residual; each touched entry is folded in first.
+ float best_v = -INFINITY;
+ int best_i = INT_MAX;
+ for (int j = lane; j < nc; j += 32) {
+ const float q_j = q_row_ptr[j];
+ if (q_j > 0.0f) {
+ q_left += q_j;
+ const int32_t token = id_row[j];
+ const float p_j = p[token];
+ p_cand += p_j;
+ if (static_cast<unsigned>(token) < static_cast<unsigned>(vocab) &&
+ argmax_before(p_j, token, best_v, best_i)) {
+ best_v = p_j;
+ best_i = token;
+ }
+ }
+ }
+ for (int offset = 16; offset > 0; offset >>= 1) {
+ q_left += __shfl_xor_sync(0xffffffff, q_left, offset);
+ p_cand += __shfl_xor_sync(0xffffffff, p_cand, offset);
+ }
+ const float z_out = fmaxf(1.0f - p_cand, 0.0f);
+ float z = 1.0f;
+ while (child >= 0) {
+ const int pos = q_pos[q_row * num_nodes + child];
+ const int64_t child_token = tokens[(int64_t)b * num_nodes + child];
+ const float q_child = q_row_ptr[pos];
+ if (q_child > 0.0f && q_left > 0.0f && z > 0.0f) {
+ const float q_i = q_child / q_left;
+ const float r_child = p[child_token];
+ if (static_cast<uint64_t>(child_token) < static_cast<uint64_t>(vocab) &&
+ argmax_before(r_child, static_cast<int>(child_token), best_v, best_i)) {
+ best_v = r_child;
+ best_i = static_cast<int>(child_token);
+ }
+ if (coins[(int64_t)b * coins_stride + child] * q_i * z < r_child) {
+ accepted = child;
+ break;
+ }
+ const float scale = z / q_left;
+ float r_sum = 0.0f, q_sum = 0.0f;
+ for (int j = lane; j < nc; j += 32) {
+ const float q_j = q_row_ptr[j];
+ if (q_j <= 0.0f || j == pos) continue;
+ const int32_t token = id_row[j];
+ bool gone = false;
+ for (int r = 0; r < rejected_count; ++r) gone |= (rejected_pos[r] == j);
+ if (gone) {
+ r_sum += p[token];
+ continue;
+ }
+ const float r_new = fmaxf(p[token] - scale * q_j, 0.0f);
+ p[token] = r_new;
+ r_sum += r_new;
+ q_sum += q_j;
+ }
+ for (int offset = 16; offset > 0; offset >>= 1) {
+ r_sum += __shfl_xor_sync(0xffffffff, r_sum, offset);
+ q_sum += __shfl_xor_sync(0xffffffff, q_sum, offset);
+ }
+ const float r_y = fmaxf(r_child - scale * q_child, 0.0f);
+ if (lane == 0) p[child_token] = r_y;
+ __syncwarp();
+ const float z_new = z_out + r_sum + r_y;
+ if (!(z_new > 1e-6f * z)) {
+ if (r_child > 0.0f) {
+ accepted = child;
+ } else {
+ // Bonus = target's argmax: untouched entries keep target values (rare, so scanned).
+ for (int j = lane; j < vocab; j += 32) {
+ const float v = p[j];
+ if (argmax_before(v, j, best_v, best_i)) {
+ best_v = v;
+ best_i = j;
+ }
+ }
+ for (int offset = 16; offset > 0; offset >>= 1) {
+ const float other_v = __shfl_xor_sync(0xffffffff, best_v, offset);
+ const int other_i = __shfl_xor_sync(0xffffffff, best_i, offset);
+ if (argmax_before(other_v, other_i, best_v, best_i)) {
+ best_v = other_v;
+ best_i = other_i;
+ }
+ }
+ if (lane == 0) p[best_i] = 1.0f;
+ __syncwarp();
+ }
+ break;
+ }
+ z = z_new;
+ q_left = q_sum;
+ if (rejected_count < MAX_SAMPLED_CHILDREN) rejected_pos[rejected_count++] = pos;
+ }
+ child = next_child(s_parent, node, child, num_nodes);
+ }
+ } else if (lane == 0 && greedy) {
+ const int64_t best = argmax[row];
+ while (child >= 0 && tokens[(int64_t)b * num_nodes + child] != best) {
+ child = next_child(s_parent, node, child, num_nodes);
+ }
+ accepted = child;
+ } else if (lane == 0) {
+ float total = 1.0f;
+ while (child >= 0) {
+ const int64_t child_token = tokens[(int64_t)b * num_nodes + child];
+ if (static_cast<uint64_t>(child_token) < static_cast<uint64_t>(vocab)) {
+ const float child_proba = p[child_token];
+ // Accepts with probability p'(child) over the mass its rejected siblings left.
+ if (child_proba > 0.0f &&
+ coins[(int64_t)b * coins_stride + child] * total < child_proba) {
+ accepted = child;
+ break;
+ }
+ total = fmaxf(total - child_proba, 0.0f);
+ p[child_token] = 0.0f;
+ }
+ child = next_child(s_parent, node, child, num_nodes);
+ }
+ }
+ if (lane == 0) s_accept_child[node] = accepted;
+ }
+ __syncthreads();
+ if (threadIdx.x == 0) {
+ int32_t* path_b = path + (int64_t)b * num_nodes;
+ int32_t* predicts_b = predicts + (int64_t)b * num_nodes;
+ int length = 1;
+ int node = 0;
+ path_b[0] = 0;
+ for (int c = s_accept_child[0]; c >= 0; c = s_accept_child[node]) {
+ predicts_b[length - 1] = tokens[(int64_t)b * num_nodes + c];
+ path_b[length++] = c;
+ node = c;
+ }
+ for (int i = length; i < num_nodes; ++i) path_b[i] = -1;
+ accept_length[b] = length;
+ last_row[b] = (int64_t)b * num_nodes + node;
+ }
+}
+
+// Bonus token: inverse-CDF draw from the last accepted node's unnormalized row; greedy: its argmax.
+constexpr int RESIDUAL_SAMPLE_THREADS = 1024;
+// Runs of 16 staged in shared memory coalesce the loads; each lane still sums its segment in order.
+constexpr int RESIDUAL_SAMPLE_RUN = 16;
+static_assert(32 % RESIDUAL_SAMPLE_RUN == 0, "a warp load stages whole runs");
+constexpr int RESIDUAL_SAMPLE_SMEM_BYTES =
+ RESIDUAL_SAMPLE_THREADS * (RESIDUAL_SAMPLE_RUN + 1) * sizeof(float);
+
+__global__ void __launch_bounds__(RESIDUAL_SAMPLE_THREADS)
+ residual_sample_kernel(const float* __restrict__ probas, int64_t probas_stride,
+ const int64_t* __restrict__ last_row, const float* __restrict__ coins,
+ const int32_t* __restrict__ top_ks,
+ const int64_t* __restrict__ argmax,
+ const int32_t* __restrict__ accept_length,
+ int32_t* __restrict__ predicts, int num_nodes, int vocab) {
+ const int b = blockIdx.x;
+ const int64_t row = last_row[b];
+ if (top_ks[row] == 1) {
+ if (threadIdx.x == 0) {
+ predicts[(int64_t)b * num_nodes + accept_length[b] - 1] = static_cast<int32_t>(argmax[row]);
+ }
+ return;
+ }
+ const float* p = probas + row * probas_stride;
+ const int seg = (vocab + RESIDUAL_SAMPLE_THREADS - 1) / RESIDUAL_SAMPLE_THREADS;
+ const int start = min(threadIdx.x * seg, vocab);
+ const int end = min(start + seg, vocab);
+ const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
+ extern __shared__ float s_runs[];
+ // Row r of this warp's [32, RUN + 1] tile holds a run of lane r's segment.
+ float* runs = s_runs + warp * 32 * (RESIDUAL_SAMPLE_RUN + 1);
+ // A warp load stages 32 / RUN runs: lane l fills column l % RUN of run l / RUN.
+ const int col = lane % RESIDUAL_SAMPLE_RUN;
+ float local = 0.0f;
+ int last_positive = -1;
+ for (int c = 0; c < seg; c += RESIDUAL_SAMPLE_RUN) {
+#pragma unroll
+ for (int r0 = 0; r0 < 32; r0 += 32 / RESIDUAL_SAMPLE_RUN) {
+ const int r = r0 + lane / RESIDUAL_SAMPLE_RUN;
+ const int r_start = min((warp * 32 + r) * seg, vocab);
+ const int i = r_start + c + col;
+ runs[r * (RESIDUAL_SAMPLE_RUN + 1) + col] =
+ i < min(r_start + seg, vocab) ? p[i] : 0.0f;
+ }
+ __syncwarp();
+ const int n = min(RESIDUAL_SAMPLE_RUN, end - start - c);
+ for (int j = 0; j < n; ++j) {
+ const float v = runs[lane * (RESIDUAL_SAMPLE_RUN + 1) + j];
+ local += v;
+ if (v > 0.0f) last_positive = start + c + j;
+ }
+ __syncwarp();
+ }
+ // Inclusive scan of the segment sums over the block.
+ __shared__ float s_warp[RESIDUAL_SAMPLE_THREADS / 32];
+ __shared__ int s_last[RESIDUAL_SAMPLE_THREADS / 32];
+ __shared__ int s_token;
+ float incl = local;
+ int last = last_positive;
+ for (int offset = 1; offset < 32; offset <<= 1) {
+ const float u = __shfl_up_sync(0xffffffff, incl, offset);
+ if (lane >= offset) incl += u;
+ }
+ for (int offset = 16; offset > 0; offset >>= 1) last = max(last, __shfl_xor_sync(0xffffffff, last, offset));
+ if (lane == 31) s_warp[warp] = incl;
+ if (lane == 0) s_last[warp] = last;
+ if (threadIdx.x == 0) s_token = INT_MAX;
+ __syncthreads();
+ float before = 0.0f, total = 0.0f;
+ int any_last = -1;
+ for (int w = 0; w < RESIDUAL_SAMPLE_THREADS / 32; ++w) {
+ if (w < warp) before += s_warp[w];
+ total += s_warp[w];
+ any_last = max(any_last, s_last[w]);
+ }
+ const float exclusive = before + incl - local;
+ const float target = coins[b] * total;
+ // A claiming lane rescans its segment, staged run by run through its warp's tile.
+ const bool claim = local > 0.0f && exclusive <= target && target < exclusive + local;
+ for (unsigned claims = __ballot_sync(0xffffffff, claim); claims != 0; claims &= claims - 1) {
+ const int r = __ffs(claims) - 1;
+ const int r_start = __shfl_sync(0xffffffff, start, r);
+ const int r_end = __shfl_sync(0xffffffff, end, r);
+ float acc = exclusive;
+ for (int c = r_start; c < r_end; c += RESIDUAL_SAMPLE_RUN) {
+ if (lane < RESIDUAL_SAMPLE_RUN) runs[lane] = c + lane < r_end ? p[c + lane] : 0.0f;
+ __syncwarp();
+ int token = -1;
+ if (lane == r) {
+ const int n = min(RESIDUAL_SAMPLE_RUN, r_end - c);
+ for (int j = 0; j < n; ++j) {
+ acc += runs[j];
+ if (acc > target && runs[j] > 0.0f) {
+ token = c + j;
+ break;
+ }
+ }
+ }
+ token = __shfl_sync(0xffffffff, token, r);
+ __syncwarp();
+ if (token >= 0) {
+ // Rounding can make neighbouring segments overlap: the lowest claim wins.
+ if (lane == 0) atomicMin(&s_token, token);
+ break;
+ }
+ }
+ }
+ __syncthreads();
+ if (threadIdx.x == 0) {
+ // Rounding can also leave the target in a gap, or at the very end of the mass.
+ const int token = s_token != INT_MAX ? s_token : max(any_last, 0);
+ predicts[(int64_t)b * num_nodes + accept_length[b] - 1] = token;
+ }
+}
+
+void tree_reject_sample(TensorView probas, TensorView tokens, TensorView parents,
+ Optional<TensorView> q_rows, TensorView q_slot,
+ TensorView q_pos, TensorView q_store, TensorView qid_store,
+ TensorView coins, TensorView top_ks, TensorView argmax,
+ TensorView path, TensorView predicts,
+ TensorView accept_length, TensorView last_row) {
+ TVM_FFI_ICHECK(probas.stride(1) == 1 && coins.stride(1) == 1);
+ const int batch_size = static_cast<int>(tokens.size(0));
+ const int num_nodes = static_cast<int>(tokens.size(1));
+ TVM_FFI_ICHECK_LE(num_nodes, MAX_TREE_NODES);
+ // The kernel indexes the trees and their q tables with the trees' row width.
+ TVM_FFI_ICHECK(tokens.stride(0) == num_nodes && parents.size(1) == num_nodes &&
+ parents.stride(0) == num_nodes && coins.size(1) >= num_nodes &&
+ probas.size(0) >= static_cast<int64_t>(batch_size) * num_nodes)
+ << "tree_reject_sample: row widths";
+ TVM_FFI_ICHECK(top_ks.ndim() == 1 && top_ks.stride(0) == 1 && argmax.ndim() == 1 &&
+ argmax.stride(0) == 1 &&
+ top_ks.size(0) >= static_cast<int64_t>(batch_size) * num_nodes &&
+ argmax.size(0) >= static_cast<int64_t>(batch_size) * num_nodes)
+ << "tree_reject_sample: one top-k and argmax per row";
+ if (q_rows.has_value()) {
+ TVM_FFI_ICHECK(q_slot.size(1) == num_nodes && q_pos.size(1) == num_nodes &&
+ q_slot.stride(0) == num_nodes && q_pos.stride(0) == num_nodes)
+ << "tree_reject_sample: q table row widths";
+ }
+ if (batch_size == 0) return;
+ const bool sampled = q_rows.has_value();
+ const int threads = std::min(1024, 32 * num_nodes);
+ tree_reject_sample_kernel<<<batch_size, threads, 0, get_stream(probas.device())>>>(
+ static_cast<float*>(probas.data_ptr()), probas.stride(0),
+ static_cast<const int32_t*>(tokens.data_ptr()), static_cast<const int32_t*>(parents.data_ptr()),
+ sampled ? static_cast<const int64_t*>(q_rows.value().data_ptr()) : nullptr,
+ static_cast<const int32_t*>(q_slot.data_ptr()), static_cast<const int32_t*>(q_pos.data_ptr()),
+ static_cast<const float*>(q_store.data_ptr()),
+ static_cast<const int32_t*>(qid_store.data_ptr()), static_cast<const float*>(coins.data_ptr()),
+ coins.stride(0), static_cast<const int32_t*>(top_ks.data_ptr()),
+ static_cast<const int64_t*>(argmax.data_ptr()), static_cast<int32_t*>(path.data_ptr()),
+ static_cast<int32_t*>(predicts.data_ptr()), static_cast<int32_t*>(accept_length.data_ptr()),
+ static_cast<int64_t*>(last_row.data_ptr()), num_nodes, static_cast<int>(q_store.size(1)),
+ static_cast<int>(q_store.size(2)), static_cast<int>(probas.size(1)));
+}
+
+void residual_sample(TensorView probas, TensorView last_row, TensorView coins,
+ TensorView top_ks, TensorView argmax, TensorView accept_length,
+ TensorView predicts, int64_t num_nodes) {
+ TVM_FFI_ICHECK_EQ(probas.stride(1), 1);
+ const int batch_size = static_cast<int>(last_row.size(0));
+ TVM_FFI_ICHECK(predicts.size(0) >= batch_size * num_nodes && accept_length.size(0) >= batch_size)
+ << "residual_sample: output rows";
+ // last_row indexes probas rows, and so the per-row top-k and argmax.
+ TVM_FFI_ICHECK(top_ks.ndim() == 1 && top_ks.stride(0) == 1 && argmax.ndim() == 1 &&
+ argmax.stride(0) == 1 && top_ks.size(0) >= probas.size(0) &&
+ argmax.size(0) >= probas.size(0))
+ << "residual_sample: one top-k and argmax per row";
+ if (batch_size == 0) return;
+ // The opt-in to over 48 KB of dynamic shared memory is per device: once each.
+ static std::atomic<uint64_t> opted_in{0};
+ const int device = probas.device().device_id;
+ TVM_FFI_ICHECK(device < 64) << "residual_sample: device " << device;
+ if (!((opted_in.load(std::memory_order_relaxed) >> device) & 1)) {
+ const cudaError_t smem_status = cudaFuncSetAttribute(
+ residual_sample_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize,
+ RESIDUAL_SAMPLE_SMEM_BYTES);
+ TVM_FFI_ICHECK(smem_status == cudaSuccess)
+ << "residual_sample: " << cudaGetErrorString(smem_status);
+ opted_in.fetch_or(uint64_t{1} << device, std::memory_order_relaxed);
+ }
+ residual_sample_kernel<<<batch_size, RESIDUAL_SAMPLE_THREADS, RESIDUAL_SAMPLE_SMEM_BYTES,
+ get_stream(probas.device())>>>(
+ static_cast<const float*>(probas.data_ptr()), probas.stride(0),
+ static_cast<const int64_t*>(last_row.data_ptr()), static_cast<const float*>(coins.data_ptr()),
+ static_cast<const int32_t*>(top_ks.data_ptr()), static_cast<const int64_t*>(argmax.data_ptr()),
+ static_cast<const int32_t*>(accept_length.data_ptr()),
+ static_cast<int32_t*>(predicts.data_ptr()), static_cast<int>(num_nodes),
+ static_cast<int>(probas.size(1)));
+}
+
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(tree_reject_sample, tree_reject_sample);
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(residual_sample, residual_sample);
diff --git a/eagle_harness/tokenspeed/tree_round/ops/csrc/eagle_harness_tree.cu b/eagle_harness/tokenspeed/tree_round/ops/csrc/eagle_harness_tree.cu
new file mode 100644
index 0000000..d13def4
--- /dev/null
+++ b/eagle_harness/tokenspeed/tree_round/ops/csrc/eagle_harness_tree.cu
@@ -0,0 +1,1385 @@
+// Copyright 2026 Eagle AI Corp.
+// SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+#include <curand_kernel.h>
+
+#include <algorithm>
+#include <cfloat>
+#include <climits>
+#include <cstdint>
+#include <utility>
+
+#include "tvm_ffi_utils.h"
+
+using tvm::ffi::Optional;
+
+constexpr int MAX_BATCH_SIZE = 512; // live and padded requests
+constexpr float DEPTH_DECAY = 0.9999f; // a pool node's score: path score * DEPTH_DECAY^depth
+constexpr int MAX_TREE_NODES = 64; // verify tree nodes per request
+
+// ---------------------------------------------------------------------------
+// The root's children: the first level of the pool, the work and sort lists.
+// ---------------------------------------------------------------------------
+__global__ void update_node_data_kernel(
+ float* __restrict__ cumu_scores, int64_t* __restrict__ cumu_tokens,
+ float* __restrict__ work_scores, float* __restrict__ sort_scores,
+ const float* __restrict__ output_scores, const int64_t* __restrict__ output_tokens,
+ int batch_size, int node_top_k, int stride_cumu, int stride_work, int stride_sort) {
+ int idx = blockIdx.x * blockDim.x + threadIdx.x;
+ int total_elements = batch_size * node_top_k;
+ if (idx < total_elements) {
+ int b = idx / node_top_k;
+ int k = idx % node_top_k;
+ int target_col = k + 1; // start = 1
+ float score = output_scores[idx];
+ int64_t token = output_tokens[idx];
+ cumu_scores[b * stride_cumu + target_col] = score;
+ cumu_tokens[b * stride_cumu + target_col] = token;
+ work_scores[b * stride_work + target_col] = score;
+ sort_scores[b * stride_sort + target_col] = score;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Work deltas: work_deltas[j] is the batch mean of the best min(node_count + j,
+// verify_num) scores among the two sorted segments of a row (the current best
+// node_count scores, then the next depth's j best frontier scores), over the
+// first *live_rows rows (a graph's padded rows sum as zeros). The counts are
+// device scalars; a zero node count queues no deltas.
+//
+// One thread per row, summed by the reference's 256-thread halving tree.
+// Padded threads contribute zeros, preserving its floating-point order.
+// ---------------------------------------------------------------------------
+template <int kThreads>
+__global__ void calculate_work_deltas_kernel(const float* __restrict__ work_scores,
+ float* __restrict__ work_deltas,
+ const int* __restrict__ live_rows, int total_cols,
+ const int* __restrict__ node_count_ptr,
+ const int* __restrict__ verify_num_ptr) {
+ const int node_count = *node_count_ptr;
+ if (node_count == 0) return;
+ const int j = blockIdx.x;
+ const int tid = threadIdx.x;
+ const int batch_size = *live_rows;
+ const int verify_num = *verify_num_ptr;
+ if (batch_size == 0) return; // Warm-up has no live round.
+ if (batch_size < 0 || batch_size > MAX_BATCH_SIZE || node_count < 0 ||
+ node_count + gridDim.x - 1 > total_cols || verify_num < 1 || verify_num > 64) {
+ __trap();
+ return;
+ }
+
+ __shared__ float s_reduction_sums[kThreads];
+
+ float row_sum = 0.0f;
+ if (tid < batch_size) {
+ const int slice_len = node_count + j;
+ const int k = min(slice_len, verify_num);
+
+ const float* temp_scores_ptr = work_scores + tid * total_cols;
+ const float* topk_scores_ptr = temp_scores_ptr + node_count;
+
+ int pA = 0;
+ int pB = 0;
+ for (int i = 0; i < k; ++i) {
+ float val_a = (pA < node_count) ? temp_scores_ptr[pA] : 0.0f;
+ float val_b = (pB < j) ? topk_scores_ptr[pB] : 0.0f;
+ if (val_a >= val_b) {
+ row_sum += val_a;
+ pA++;
+ } else {
+ row_sum += val_b;
+ pB++;
+ }
+ }
+ }
+
+ s_reduction_sums[tid] = row_sum;
+ __syncthreads();
+
+ for (unsigned int s = kThreads / 2; s > 0; s >>= 1) {
+ if (tid < s) s_reduction_sums[tid] += s_reduction_sums[tid + s];
+ __syncthreads();
+ }
+
+ if (tid == 0) work_deltas[j] = s_reduction_sums[0] / batch_size;
+}
+
+// ---------------------------------------------------------------------------
+// One draft depth's bookkeeping after its lane forward, one CTA per request
+// row. The expanded lanes' width * K children get path scores (child
+// probability times the lane's path score), sorted descending by a fixed
+// 64-wide bitonic network whose tie order the frontier inherits; the best K
+// become the next frontier (tokens, scores, pool indices, and their parent
+// lanes' output hidden rows). Every child is appended to the pool (score
+// times 0.9999^depth) and linked; the sort list keeps the best verify_num
+// path scores of [its head, the sorted children] by stable rank, and the work
+// list holds that head and the frontier's scores for the next work deltas.
+// The lanes move one slot on (positions + 1, slot starts + K) and, when the
+// next depth fits in the lane window, next lane r's mask row is its parent
+// lane's row plus its own slot depth * K + r.
+// ---------------------------------------------------------------------------
+// Warps 0-4 do the bookkeeping, the other 19 copy the hidden rows: enough
+// loads in flight that the copy is not latency-bound at small batch, while
+// two CTAs still fit an SM at large batch.
+constexpr int DRAFT_DEPTH_THREADS = 768;
+constexpr int DRAFT_DEPTH_COPY_THREADS = DRAFT_DEPTH_THREADS - 5 * 32;
+constexpr int DRAFT_DEPTH_MAX_CHILDREN = 64; // width * K, the sort network's size
+constexpr int DRAFT_DEPTH_MAX_VERIFY = 64; // the sort list's merged head
+constexpr int DRAFT_DEPTH_MAX_MASK_WORDS = 1;
+constexpr int DRAFT_DEPTH_COPY_UNROLL = 4;
+
+// One compare-exchange of the sort network across lanes: position p pairs
+// with p ^ stride (in lane l ^ stride / 2, the same register). The pair (i, j)
+// is exchanged when j < n and it is out of its block's order (descending when
+// bit `size` of i is clear), by strict comparison: ties and NaN never swap.
+// Both lanes evaluate the same comparison of the same two values.
+__device__ __forceinline__ void sort_exchange_lanes(float& v, int& x, int p, int stride, int size,
+ int n) {
+ const float o = __shfl_xor_sync(0xffffffff, v, stride >> 1);
+ const int ox = __shfl_xor_sync(0xffffffff, x, stride >> 1);
+ const bool lower = (p & stride) == 0;
+ const bool descending = (p & size) == 0;
+ const bool swap = ((p | stride) < n) & (lower == descending ? v < o : v > o);
+ v = swap ? o : v;
+ x = swap ? ox : x;
+}
+
+// Descending sort of n <= 64 values on one warp, lane l holding positions 2l
+// and 2l + 1 (value v, original position x): a bitonic network over 64
+// positions that skips every pair reaching past n. Positions past n keep
+// their values.
+__device__ __forceinline__ void bitonic_sort_64_warp(float& v0, int& x0, float& v1, int& x1,
+ int n) {
+ const int p0 = 2 * (threadIdx.x & 31);
+#pragma unroll
+ for (int size = 2; size <= DRAFT_DEPTH_MAX_CHILDREN; size <<= 1) {
+#pragma unroll
+ for (int stride = size >> 1; stride > 1; stride >>= 1) {
+ sort_exchange_lanes(v0, x0, p0, stride, size, n);
+ sort_exchange_lanes(v1, x1, p0 + 1, stride, size, n);
+ }
+ // Stride 1: the pair (2l, 2l + 1) sits in one lane.
+ const bool descending = (p0 & size) == 0;
+ const bool swap = (p0 + 1 < n) & (descending ? v0 < v1 : v0 > v1);
+ const float v = v0;
+ const int x = x0;
+ v0 = swap ? v1 : v0;
+ x0 = swap ? x1 : x0;
+ v1 = swap ? v : v1;
+ x1 = swap ? x : x1;
+ }
+}
+
+__global__ void __launch_bounds__(DRAFT_DEPTH_THREADS) draft_depth_update_kernel(
+ const float* __restrict__ child_probs, int64_t child_probs_s0, int64_t child_probs_s1,
+ const int64_t* __restrict__ child_tokens, int64_t child_tokens_s0, int64_t child_tokens_s1,
+ const int64_t* __restrict__ expanded, int64_t expanded_s0,
+ const uint4* __restrict__ child_hidden, int64_t child_hidden_s0, int64_t child_hidden_s1,
+ int64_t* __restrict__ frontier_tokens, int64_t frontier_tokens_s0,
+ float* __restrict__ frontier_scores, int64_t frontier_scores_s0,
+ uint4* __restrict__ frontier_hidden, int64_t frontier_hidden_s0, int64_t frontier_hidden_s1,
+ int64_t* __restrict__ frontier_index, int64_t frontier_index_s0,
+ int64_t* __restrict__ pool_tokens, float* __restrict__ pool_scores,
+ int64_t* __restrict__ pool_depths, int64_t* __restrict__ pool_prev,
+ int64_t* __restrict__ pool_next, int64_t* __restrict__ pool_side, int64_t node_stride,
+ int num_nodes, float* __restrict__ work_scores, int64_t work_stride,
+ float* __restrict__ sort_scores, int64_t sort_stride, int64_t* __restrict__ positions,
+ int64_t positions_s0, int64_t* __restrict__ slot_starts, int64_t slot_starts_s0,
+ int64_t* __restrict__ lane_mask, int64_t lane_mask_s0, int64_t lane_mask_s1, int mask_words,
+ int node_top_k, const int* __restrict__ width_ptr, int depth,
+ const int* __restrict__ cumu_count_ptr, const int* __restrict__ verify_num_ptr, int num_slots,
+ int vecs_per_row) {
+ const int b = blockIdx.x;
+ const int tid = threadIdx.x;
+ const int warp = tid >> 5;
+ const int lane = tid & 31;
+ const int k = node_top_k;
+ const int width = *width_ptr;
+ // A sampled plan may stop at the root; depth 1 still runs its captured forward.
+ if (width == 0) return;
+ const int cumu_count = *cumu_count_ptr;
+ const int verify_num = *verify_num_ptr;
+ if (width < 1 || width > k || cumu_count < 1 || cumu_count + width * k > num_nodes ||
+ verify_num < 1 || verify_num > DRAFT_DEPTH_MAX_VERIFY) {
+ __trap();
+ return;
+ }
+ const int n = width * k;
+ const int head = min(verify_num, cumu_count); // sort list entries merged with the children
+ const int kept = min(verify_num, cumu_count + n); // sort list entries after the merge
+ const int child_depth = depth + 1;
+
+ __shared__ float s_scores[DRAFT_DEPTH_MAX_CHILDREN]; // children's path scores, sorted
+ __shared__ int s_order[DRAFT_DEPTH_MAX_CHILDREN]; // their child positions
+ __shared__ int s_parent[DRAFT_DEPTH_MAX_CHILDREN]; // the frontier's parent lanes
+ __shared__ int64_t s_tokens[DRAFT_DEPTH_MAX_CHILDREN]; // children's tokens, unsorted
+ __shared__ float s_head[DRAFT_DEPTH_MAX_VERIFY];
+ __shared__ int64_t s_mask[DRAFT_DEPTH_MAX_CHILDREN * DRAFT_DEPTH_MAX_MASK_WORDS];
+
+ const float* probs = child_probs + b * child_probs_s0;
+ const int64_t* tokens = child_tokens + b * child_tokens_s0;
+ const int64_t* parents = expanded + b * expanded_s0;
+ float* scores = frontier_scores + b * frontier_scores_s0;
+ const int64_t node_row = b * node_stride;
+
+ // Reads of the frontier scores, sort list and lane masks, all before the
+ // barrier that orders them ahead of their rewrites. Every lane's children
+ // are read, not only the expanded ones, so the reads need not wait for the
+ // device counts; children past n are dropped.
+ if (warp == 0) {
+ const int p0 = 2 * lane;
+ const int p1 = p0 + 1;
+ float v0 = p0 < k * k ? probs[(p0 / k) * child_probs_s1 + p0 % k] * scores[p0 / k] : 0.0f;
+ float v1 = p1 < k * k ? probs[(p1 / k) * child_probs_s1 + p1 % k] * scores[p1 / k] : 0.0f;
+ v0 = p0 < n ? v0 : -1e10f;
+ v1 = p1 < n ? v1 : -1e10f;
+ int x0 = p0;
+ int x1 = p1;
+ bitonic_sort_64_warp(v0, x0, v1, x1, n);
+ s_scores[p0] = v0;
+ s_scores[p1] = v1;
+ s_order[p0] = x0;
+ s_order[p1] = x1;
+ __syncwarp();
+ for (int i = lane; i < k; i += 32) s_parent[i] = s_order[i] / k;
+ } else if (warp == 1) {
+ // The children's pool tokens and scores.
+ const float depth_decay = powf(DEPTH_DECAY, (float)child_depth);
+ for (int t = lane; t < k * k; t += 32) {
+ const int r = t / k;
+ const int64_t token = tokens[r * child_tokens_s1 + t % k];
+ const float score = probs[r * child_probs_s1 + t % k] * scores[r];
+ if (t >= n) continue;
+ s_tokens[t] = token;
+ const int node = cumu_count + t;
+ pool_tokens[node_row + node] = token;
+ pool_scores[node_row + node] = score * depth_decay;
+ }
+ } else if (warp == 2) {
+ // The children's depth, parent, first child (none yet) and next sibling.
+ for (int t = lane; t < k * k; t += 32) {
+ const int64_t parent = parents[t / k];
+ if (t >= n) continue;
+ const int node = cumu_count + t;
+ pool_depths[node_row + node] = child_depth;
+ pool_prev[node_row + node] = parent;
+ pool_next[node_row + node] = -1;
+ pool_side[node_row + node] = t % k == k - 1 ? -1 : node + 1;
+ }
+ } else if (warp == 3) {
+ for (int i = lane; i < head; i += 32) {
+ const float v = sort_scores[b * sort_stride + i];
+ s_head[i] = v;
+ work_scores[b * work_stride + i] = v;
+ }
+ } else if (warp == 4) {
+ for (int t = lane; t < k * mask_words; t += 32) {
+ const int r = t / mask_words;
+ s_mask[t] = lane_mask[b * lane_mask_s0 + r * lane_mask_s1 + t % mask_words];
+ }
+ for (int r = lane; r < k; r += 32) positions[b * positions_s0 + r] += 1;
+ if (lane == 0) slot_starts[b * slot_starts_s0] += k;
+ }
+ __syncthreads();
+
+ if (warp == 0) {
+ for (int i = lane; i < k; i += 32) {
+ const int child = s_order[i];
+ frontier_index[b * frontier_index_s0 + i] = cumu_count + child;
+ scores[i] = s_scores[i];
+ frontier_tokens[b * frontier_tokens_s0 + i] = s_tokens[child];
+ work_scores[b * work_stride + head + i] = s_scores[i];
+ }
+ // The expanded lanes' first children (after the children's own -1).
+ for (int r = lane; r < width; r += 32) {
+ const int64_t parent = parents[r];
+ if (parent >= 0 && parent < num_nodes) pool_next[node_row + parent] = cumu_count + r * k;
+ }
+ if ((depth + 1) * k <= num_slots) {
+ for (int t = lane; t < k * mask_words; t += 32) {
+ const int i = t / mask_words;
+ const int word = t % mask_words;
+ const int slot = depth * k + i;
+ uint64_t bits = static_cast<uint64_t>(s_mask[s_parent[i] * mask_words + word]);
+ if (slot / 64 == word) bits |= uint64_t{1} << (slot % 64);
+ lane_mask[b * lane_mask_s0 + i * lane_mask_s1 + word] = static_cast<int64_t>(bits);
+ }
+ }
+ } else if (warp <= 4) {
+ // Stable rank of each entry of [sort list head, sorted children]; the
+ // best `kept` land at their rank.
+ const int total = head + n;
+ for (int e = tid - 32; e < total; e += 4 * 32) {
+ const float key = e < head ? s_head[e] : s_scores[e - head];
+ int rank = 0;
+ for (int j = 0; j < total; ++j) {
+ const float v = j < head ? s_head[j] : s_scores[j - head];
+ rank += (v > key) || (v == key && j < e);
+ }
+ if (rank < kept) sort_scores[b * sort_stride + rank] = key;
+ }
+ } else {
+ // The frontier's input hidden rows: their parent lanes' output rows.
+ const int total_vecs = k * vecs_per_row;
+ const uint4* hidden_in = child_hidden + b * child_hidden_s0;
+ uint4* hidden_out = frontier_hidden + b * frontier_hidden_s0;
+ constexpr int step = DRAFT_DEPTH_COPY_UNROLL * DRAFT_DEPTH_COPY_THREADS;
+ for (int base = tid - 5 * 32; base < total_vecs; base += step) {
+ uint4 data[DRAFT_DEPTH_COPY_UNROLL];
+#pragma unroll
+ for (int u = 0; u < DRAFT_DEPTH_COPY_UNROLL; ++u) {
+ const int v = base + u * DRAFT_DEPTH_COPY_THREADS;
+ if (v < total_vecs) {
+ const int i = v / vecs_per_row;
+ data[u] = hidden_in[s_parent[i] * child_hidden_s1 + (v - i * vecs_per_row)];
+ }
+ }
+#pragma unroll
+ for (int u = 0; u < DRAFT_DEPTH_COPY_UNROLL; ++u) {
+ const int v = base + u * DRAFT_DEPTH_COPY_THREADS;
+ if (v < total_vecs) {
+ const int i = v / vecs_per_row;
+ hidden_out[i * frontier_hidden_s1 + (v - i * vecs_per_row)] = data[u];
+ }
+ }
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// The first k entries of a stable descending sort per row (NaN first, then
+// descending value, ties by ascending index), the order verification ranks
+// pool nodes in: a parent always precedes its equal-scored children. The
+// order is a strict total one, so any power-of-two network width p >= n and
+// any thread count give the same first n entries.
+// ---------------------------------------------------------------------------
+__device__ __forceinline__ bool stable_desc_before(float av, int ai, float bv, int bi, int n) {
+ if (ai >= n) return false;
+ if (bi >= n) return true;
+ const bool an = isnan(av);
+ const bool bn = isnan(bv);
+ if (an != bn) return an;
+ if (!an && av != bv) return av > bv;
+ return ai < bi;
+}
+
+__global__ void stable_topk_desc_kernel(const float* __restrict__ scores, int64_t row_stride,
+ const int* __restrict__ live_rows,
+ const int* __restrict__ n_ptr,
+ const int* __restrict__ k_ptr,
+ float* __restrict__ out_values,
+ int64_t* __restrict__ out_indices, int64_t out_stride) {
+ __shared__ float key[1024];
+ __shared__ int idx[1024];
+ const int row = blockIdx.x;
+ if (row >= *live_rows) return;
+ const int n = *n_ptr;
+ const int k = *k_ptr;
+ if (n < 1 || n > 1024 || k < 1 || k > n) {
+ __trap();
+ return;
+ }
+ int p = 1;
+ while (p < n) p <<= 1;
+ const float* in = scores + row * row_stride;
+ for (int i = threadIdx.x; i < p; i += blockDim.x) {
+ key[i] = i < n ? in[i] : 0.0f;
+ idx[i] = i;
+ }
+ __syncthreads();
+ for (int size = 2; size <= p; size <<= 1) {
+ for (int stride = size >> 1; stride > 0; stride >>= 1) {
+ for (int i = threadIdx.x; i < p; i += blockDim.x) {
+ const int j = i ^ stride;
+ if (j > i) {
+ const float vi = key[i], vj = key[j];
+ const int ii = idx[i], ij = idx[j];
+ const bool j_first = stable_desc_before(vj, ij, vi, ii, n);
+ const bool swap = ((i & size) == 0) ? j_first : !j_first;
+ if (swap) {
+ key[i] = vj;
+ key[j] = vi;
+ idx[i] = ij;
+ idx[j] = ii;
+ }
+ }
+ }
+ __syncthreads();
+ }
+ }
+ for (int i = threadIdx.x; i < k; i += blockDim.x) {
+ out_values[row * out_stride + i] = key[i];
+ out_indices[row * out_stride + i] = idx[i];
+ }
+}
+
+// ---------------------------------------------------------------------------
+// The round's verify tree into the next round's inputs: slot i < verify_num is
+// ranked node i (its token; its parent's slot, earlier in ancestor-first
+// order), later slots repeat the root with parent -1. One CTA per request.
+// ---------------------------------------------------------------------------
+__global__ void write_verify_tree_kernel(
+ const int64_t* __restrict__ ranked, int64_t ranked_stride,
+ const int64_t* __restrict__ cumu_tokens, const int64_t* __restrict__ prev_indexs,
+ int64_t node_stride, const int32_t* __restrict__ root_tokens, const int64_t* __restrict__ rows,
+ int32_t* __restrict__ input_map, int64_t input_stride, int32_t* __restrict__ parent_map,
+ int64_t parent_stride, const int* __restrict__ live_rows,
+ const int* __restrict__ verify_num_ptr, int num_slots) {
+ __shared__ int64_t s_nodes[MAX_TREE_NODES];
+ const int b = blockIdx.x;
+ if (b >= *live_rows) return;
+ const int verify_num = *verify_num_ptr;
+ if (verify_num < 1 || verify_num > num_slots || verify_num > MAX_TREE_NODES) {
+ __trap();
+ return;
+ }
+ for (int i = threadIdx.x; i < verify_num; i += blockDim.x) {
+ s_nodes[i] = ranked[b * ranked_stride + i];
+ }
+ __syncthreads();
+ const int64_t row = rows[b];
+ for (int i = threadIdx.x; i < num_slots; i += blockDim.x) {
+ int32_t token = root_tokens[b];
+ int32_t parent = -1;
+ if (i < verify_num) {
+ const int64_t node = s_nodes[i];
+ token = static_cast<int32_t>(cumu_tokens[b * node_stride + node]);
+ const int64_t prev = prev_indexs[b * node_stride + node];
+ for (int j = 0; j < i; ++j) {
+ if (s_nodes[j] == prev) parent = j;
+ }
+ }
+ input_map[row * input_stride + i] = token;
+ parent_map[row * parent_stride + i] = parent;
+ }
+}
+
+void eagle_harness_update_node_data(TensorView cumu_scores, TensorView cumu_tokens,
+ TensorView work_scores, TensorView sort_scores,
+ TensorView output_scores, TensorView output_tokens) {
+ const DLDevice device = output_scores.device();
+ for (const TensorView* t : {&cumu_scores, &work_scores, &sort_scores, &output_scores}) {
+ check_tensor(*t, dl_float32, device);
+ TVM_FFI_ICHECK(t->ndim() == 2 && t->stride(1) == 1);
+ }
+ for (const TensorView* t : {&cumu_tokens, &output_tokens}) {
+ check_tensor(*t, dl_int64, device);
+ TVM_FFI_ICHECK(t->ndim() == 2 && t->stride(1) == 1);
+ }
+ TVM_FFI_ICHECK(output_scores.IsContiguous() && output_tokens.IsContiguous());
+ TVM_FFI_ICHECK_EQ(cumu_tokens.stride(0), cumu_scores.stride(0));
+ const int batch_size = output_scores.size(0);
+ const int node_top_k = output_scores.size(1);
+ TVM_FFI_ICHECK(batch_size <= MAX_BATCH_SIZE &&
+ (node_top_k == 1 || node_top_k == 2 || node_top_k == 4 || node_top_k == 8));
+ TVM_FFI_ICHECK(output_tokens.size(0) == batch_size && output_tokens.size(1) == node_top_k);
+ for (const TensorView* t : {&cumu_scores, &cumu_tokens, &work_scores, &sort_scores}) {
+ TVM_FFI_ICHECK(t->size(0) >= batch_size && t->size(1) >= node_top_k + 1);
+ }
+ const int total_elements = batch_size * node_top_k;
+ if (total_elements == 0) return;
+ const int threads = 256;
+ const int blocks = (total_elements + threads - 1) / threads;
+ update_node_data_kernel<<<blocks, threads, 0, get_stream(output_scores.device())>>>(
+ static_cast<float*>(cumu_scores.data_ptr()), static_cast<int64_t*>(cumu_tokens.data_ptr()),
+ static_cast<float*>(work_scores.data_ptr()), static_cast<float*>(sort_scores.data_ptr()),
+ static_cast<const float*>(output_scores.data_ptr()),
+ static_cast<const int64_t*>(output_tokens.data_ptr()), batch_size, node_top_k,
+ cumu_scores.stride(0), work_scores.stride(0), sort_scores.stride(0));
+}
+
+void eagle_harness_work_deltas(TensorView work_scores, TensorView work_deltas, TensorView live_rows,
+ TensorView node_count, int64_t node_top_k, TensorView verify_num) {
+ check_tensor(work_scores, dl_float32, work_scores.device());
+ check_tensor(work_deltas, dl_float32, work_scores.device());
+ for (const TensorView* t : {&live_rows, &node_count, &verify_num})
+ check_scalar(*t, dl_int32, work_scores.device());
+ TVM_FFI_ICHECK(work_scores.ndim() == 2 && work_scores.IsContiguous() &&
+ work_deltas.IsContiguous());
+ TVM_FFI_ICHECK(node_top_k == 1 || node_top_k == 2 || node_top_k == 4 || node_top_k == 8);
+ TVM_FFI_ICHECK_LE(work_scores.size(0), MAX_BATCH_SIZE);
+ TVM_FFI_ICHECK_EQ(work_deltas.size(0), node_top_k + 1);
+ const auto launch = [&](auto kernel, int threads) {
+ kernel<<<node_top_k + 1, threads, 0, get_stream(work_scores.device())>>>(
+ static_cast<const float*>(work_scores.data_ptr()),
+ static_cast<float*>(work_deltas.data_ptr()), static_cast<const int*>(live_rows.data_ptr()),
+ work_scores.size(1), static_cast<const int*>(node_count.data_ptr()),
+ static_cast<const int*>(verify_num.data_ptr()));
+ };
+ // Padded graph rows determine the reference reduction shape.
+ if (work_scores.size(0) <= 256) {
+ launch(calculate_work_deltas_kernel<256>, 256);
+ } else {
+ launch(calculate_work_deltas_kernel<512>, 512);
+ }
+}
+
+void eagle_harness_draft_depth_update(
+ TensorView child_probs, TensorView child_tokens, TensorView expanded, TensorView child_hidden,
+ TensorView frontier_tokens, TensorView frontier_scores, TensorView frontier_hidden,
+ TensorView frontier_index, TensorView pool_tokens, TensorView pool_scores,
+ TensorView pool_depths, TensorView pool_prev, TensorView pool_next, TensorView pool_side,
+ TensorView work_scores, TensorView sort_scores, TensorView positions, TensorView slot_starts,
+ TensorView lane_mask, TensorView width, int64_t depth, TensorView cumu_count,
+ TensorView verify_num, int64_t num_slots) {
+ const DLDevice device = child_probs.device();
+ for (const TensorView* t :
+ {&child_probs, &frontier_scores, &pool_scores, &work_scores, &sort_scores})
+ check_tensor(*t, dl_float32, device);
+ for (const TensorView* t :
+ {&child_tokens, &expanded, &frontier_tokens, &frontier_index, &pool_tokens, &pool_depths,
+ &pool_prev, &pool_next, &pool_side, &positions, &slot_starts, &lane_mask})
+ check_tensor(*t, dl_int64, device);
+ check_tensor(child_hidden, child_hidden.dtype(), device);
+ check_tensor(frontier_hidden, child_hidden.dtype(), device);
+ for (const TensorView* t : {&width, &cumu_count, &verify_num}) check_scalar(*t, dl_int32, device);
+ TVM_FFI_ICHECK(child_probs.ndim() == 3 && child_tokens.ndim() == 3 && child_hidden.ndim() == 3 &&
+ frontier_hidden.ndim() == 3 && lane_mask.ndim() == 3)
+ << "eagle_harness_draft_depth_update: [rows, lanes, *] views";
+ const int64_t rows = child_probs.size(0);
+ const int64_t k = child_probs.size(1);
+ TVM_FFI_ICHECK(child_probs.size(2) == k && (k == 1 || k == 2 || k == 4 || k == 8) && rows <= MAX_BATCH_SIZE)
+ << "eagle_harness_draft_depth_update: " << k << " lanes of " << child_probs.size(2)
+ << " children";
+ TVM_FFI_ICHECK(child_tokens.size(0) == rows && child_tokens.size(1) == k &&
+ child_tokens.size(2) == k && child_probs.stride(2) == 1 &&
+ child_tokens.stride(2) == 1)
+ << "eagle_harness_draft_depth_update: children";
+ for (const TensorView* t : {&expanded, &frontier_tokens, &frontier_scores, &frontier_index,
+ &positions, &slot_starts, &pool_tokens, &pool_scores, &pool_depths,
+ &pool_prev, &pool_next, &pool_side, &work_scores, &sort_scores}) {
+ TVM_FFI_ICHECK(t->size(0) == rows && t->stride(t->ndim() - 1) == 1)
+ << "eagle_harness_draft_depth_update: per-request rows";
+ }
+ TVM_FFI_ICHECK(expanded.size(1) >= k && frontier_tokens.size(1) == k &&
+ frontier_scores.size(1) == k && frontier_index.size(1) == k &&
+ positions.size(1) == k)
+ << "eagle_harness_draft_depth_update: frontier";
+ const int64_t num_nodes = pool_tokens.size(1);
+ const int64_t node_stride = pool_tokens.stride(0);
+ for (const TensorView* t : {&pool_scores, &pool_depths, &pool_prev, &pool_next, &pool_side}) {
+ TVM_FFI_ICHECK(t->size(1) == num_nodes && t->stride(0) == node_stride)
+ << "eagle_harness_draft_depth_update: node pool";
+ }
+ // The device counts are the caller's: the pool fits every depth's children and
+ // the sort and work lists the verify sizes the policy can reach.
+ TVM_FFI_ICHECK(depth >= 1 && sort_scores.size(1) >= 1 &&
+ sort_scores.size(1) + k <= work_scores.size(1))
+ << "eagle_harness_draft_depth_update: verify lists";
+ const int64_t mask_words = lane_mask.size(2);
+ TVM_FFI_ICHECK(lane_mask.size(0) == rows && lane_mask.size(1) == k && lane_mask.stride(2) == 1 &&
+ mask_words == DRAFT_DEPTH_MAX_MASK_WORDS && num_slots >= 0 &&
+ num_slots <= 64 * mask_words)
+ << "eagle_harness_draft_depth_update: lane masks";
+ // Hidden rows move as 16-byte vectors.
+ const int64_t elem = get_element_size(child_hidden);
+ const int64_t row_bytes = child_hidden.size(2) * elem;
+ TVM_FFI_ICHECK(child_hidden.dtype() == frontier_hidden.dtype() && child_hidden.size(0) == rows &&
+ child_hidden.size(1) >= k && frontier_hidden.size(0) == rows &&
+ frontier_hidden.size(1) == k && frontier_hidden.size(2) == child_hidden.size(2) &&
+ child_hidden.stride(2) == 1 && frontier_hidden.stride(2) == 1)
+ << "eagle_harness_draft_depth_update: hidden rows";
+ TVM_FFI_ICHECK(row_bytes % 16 == 0 && (child_hidden.stride(0) * elem) % 16 == 0 &&
+ (child_hidden.stride(1) * elem) % 16 == 0 &&
+ (frontier_hidden.stride(0) * elem) % 16 == 0 &&
+ (frontier_hidden.stride(1) * elem) % 16 == 0 &&
+ reinterpret_cast<uintptr_t>(child_hidden.data_ptr()) % 16 == 0 &&
+ reinterpret_cast<uintptr_t>(frontier_hidden.data_ptr()) % 16 == 0)
+ << "eagle_harness_draft_depth_update: hidden rows must be 16-byte aligned";
+ // The copy gathers rows across threads: it cannot run in place.
+ auto span = [elem](const TensorView& t) {
+ const uintptr_t start = reinterpret_cast<uintptr_t>(t.data_ptr());
+ const int64_t last = (t.size(0) - 1) * t.stride(0) + (t.size(1) - 1) * t.stride(1) + t.size(2);
+ return std::make_pair(start, start + static_cast<uintptr_t>(last * elem));
+ };
+ const auto [in_start, in_end] = span(child_hidden);
+ const auto [out_start, out_end] = span(frontier_hidden);
+ TVM_FFI_ICHECK(rows == 0 || in_end <= out_start || out_end <= in_start)
+ << "eagle_harness_draft_depth_update: child_hidden must not overlap frontier_hidden";
+ if (rows == 0) return;
+ draft_depth_update_kernel<<<rows, DRAFT_DEPTH_THREADS, 0, get_stream(child_probs.device())>>>(
+ static_cast<const float*>(child_probs.data_ptr()), child_probs.stride(0),
+ child_probs.stride(1), static_cast<const int64_t*>(child_tokens.data_ptr()),
+ child_tokens.stride(0), child_tokens.stride(1),
+ static_cast<const int64_t*>(expanded.data_ptr()), expanded.stride(0),
+ static_cast<const uint4*>(child_hidden.data_ptr()), child_hidden.stride(0) * elem / 16,
+ child_hidden.stride(1) * elem / 16, static_cast<int64_t*>(frontier_tokens.data_ptr()),
+ frontier_tokens.stride(0), static_cast<float*>(frontier_scores.data_ptr()),
+ frontier_scores.stride(0), static_cast<uint4*>(frontier_hidden.data_ptr()),
+ frontier_hidden.stride(0) * elem / 16, frontier_hidden.stride(1) * elem / 16,
+ static_cast<int64_t*>(frontier_index.data_ptr()), frontier_index.stride(0),
+ static_cast<int64_t*>(pool_tokens.data_ptr()), static_cast<float*>(pool_scores.data_ptr()),
+ static_cast<int64_t*>(pool_depths.data_ptr()), static_cast<int64_t*>(pool_prev.data_ptr()),
+ static_cast<int64_t*>(pool_next.data_ptr()), static_cast<int64_t*>(pool_side.data_ptr()),
+ node_stride, static_cast<int>(num_nodes), static_cast<float*>(work_scores.data_ptr()),
+ work_scores.stride(0), static_cast<float*>(sort_scores.data_ptr()), sort_scores.stride(0),
+ static_cast<int64_t*>(positions.data_ptr()), positions.stride(0),
+ static_cast<int64_t*>(slot_starts.data_ptr()), slot_starts.stride(0),
+ static_cast<int64_t*>(lane_mask.data_ptr()), lane_mask.stride(0), lane_mask.stride(1),
+ static_cast<int>(mask_words), static_cast<int>(k), static_cast<const int*>(width.data_ptr()),
+ static_cast<int>(depth), static_cast<const int*>(cumu_count.data_ptr()),
+ static_cast<const int*>(verify_num.data_ptr()), static_cast<int>(num_slots),
+ static_cast<int>(row_bytes / 16));
+}
+
+void eagle_harness_stable_topk_desc(TensorView scores, TensorView live_rows, TensorView n,
+ TensorView k, TensorView out_values, TensorView out_indices) {
+ check_tensor(scores, dl_float32, scores.device());
+ check_tensor(out_values, dl_float32, scores.device());
+ check_tensor(out_indices, dl_int64, scores.device());
+ for (const TensorView* t : {&live_rows, &n, &k}) check_scalar(*t, dl_int32, scores.device());
+ TVM_FFI_ICHECK(scores.size(0) <= MAX_BATCH_SIZE);
+ TVM_FFI_ICHECK(scores.ndim() == 2 && out_values.ndim() == 2 && out_indices.ndim() == 2 &&
+ scores.stride(1) == 1 && out_values.stride(1) == 1 && out_indices.stride(1) == 1 &&
+ out_values.stride(0) == out_indices.stride(0));
+ // The caller keeps 1 <= k <= n <= the score columns, and k within the outputs.
+ const int64_t rows = scores.size(0);
+ TVM_FFI_ICHECK(scores.size(1) <= 1024 && out_values.size(0) == rows &&
+ out_indices.size(0) == rows && out_values.size(1) == out_indices.size(1))
+ << "stable_topk_desc needs <= 1024 score columns and [rows, max_k] outputs";
+ if (rows == 0) return;
+ stable_topk_desc_kernel<<<rows, 512, 0, get_stream(scores.device())>>>(
+ static_cast<const float*>(scores.data_ptr()), scores.stride(0),
+ static_cast<const int*>(live_rows.data_ptr()), static_cast<const int*>(n.data_ptr()),
+ static_cast<const int*>(k.data_ptr()), static_cast<float*>(out_values.data_ptr()),
+ static_cast<int64_t*>(out_indices.data_ptr()), out_values.stride(0));
+}
+
+void eagle_harness_write_verify_tree(TensorView ranked, TensorView cumu_tokens,
+ TensorView prev_indexs, TensorView root_tokens,
+ TensorView rows, TensorView input_map, TensorView parent_map,
+ TensorView live_rows, TensorView verify_num) {
+ const DLDevice device = ranked.device();
+ for (const TensorView* t : {&ranked, &cumu_tokens, &prev_indexs, &rows})
+ check_tensor(*t, dl_int64, device);
+ for (const TensorView* t : {&root_tokens, &input_map, &parent_map})
+ check_tensor(*t, dl_int32, device);
+ for (const TensorView* t : {&live_rows, &verify_num}) check_scalar(*t, dl_int32, device);
+ TVM_FFI_ICHECK(ranked.ndim() == 2 && cumu_tokens.ndim() == 2 && prev_indexs.ndim() == 2);
+ TVM_FFI_ICHECK(root_tokens.IsContiguous() && rows.IsContiguous());
+ TVM_FFI_ICHECK(input_map.ndim() == 2 && parent_map.ndim() == 2 && input_map.stride(1) == 1 &&
+ parent_map.stride(1) == 1 && input_map.size(1) == parent_map.size(1) &&
+ input_map.size(0) == parent_map.size(0) && input_map.size(1) <= MAX_TREE_NODES);
+ TVM_FFI_ICHECK(ranked.size(0) <= MAX_BATCH_SIZE && cumu_tokens.size(0) >= ranked.size(0) &&
+ prev_indexs.size(0) >= ranked.size(0) && rows.numel() >= ranked.size(0) &&
+ root_tokens.numel() >= ranked.size(0));
+ TVM_FFI_ICHECK(ranked.stride(1) == 1 && cumu_tokens.stride(1) == 1 && prev_indexs.stride(1) == 1);
+ TVM_FFI_ICHECK_EQ(cumu_tokens.stride(0), prev_indexs.stride(0));
+ // The caller keeps 1 <= verify_num <= the ranked columns, MAX_TREE_NODES and the slots.
+ const int64_t num_slots = input_map.size(1);
+ const int batch_size = ranked.size(0);
+ if (batch_size == 0) return;
+ write_verify_tree_kernel<<<batch_size, 64, 0, get_stream(ranked.device())>>>(
+ static_cast<const int64_t*>(ranked.data_ptr()), ranked.stride(0),
+ static_cast<const int64_t*>(cumu_tokens.data_ptr()),
+ static_cast<const int64_t*>(prev_indexs.data_ptr()), cumu_tokens.stride(0),
+ static_cast<const int32_t*>(root_tokens.data_ptr()),
+ static_cast<const int64_t*>(rows.data_ptr()), static_cast<int32_t*>(input_map.data_ptr()),
+ input_map.stride(0), static_cast<int32_t*>(parent_map.data_ptr()), parent_map.stride(0),
+ static_cast<const int*>(live_rows.data_ptr()), static_cast<const int*>(verify_num.data_ptr()),
+ static_cast<int>(num_slots));
+}
+
+// ---------------------------------------------------------------------------
+// Sampled trees (requests with temperature > 0). An expanded row's K children
+// are drawn without replacement from its draft distribution q over the
+// candidates (cut to the request's top-k / top-p) by Gumbel-top-K, keyed by
+// the row and candidate in the round's Philox stream. q and its candidate ids
+// are kept per expanded row (a slot) for the verifier, and each child records
+// its parent's slot and its position among the candidates. Greedy rows keep
+// their top-K children (slot -1).
+// ---------------------------------------------------------------------------
+constexpr int SAMPLE_CHILDREN_THREADS = 128;
+constexpr int SAMPLE_CHILDREN_PER_THREAD = 8;
+
+__device__ __forceinline__ void block_argmax_128(float& v, int& i, float* red_v, int* red_i) {
+ for (int offset = 16; offset > 0; offset >>= 1) {
+ const float ov = __shfl_xor_sync(0xffffffff, v, offset);
+ const int oi = __shfl_xor_sync(0xffffffff, i, offset);
+ if (ov > v || (ov == v && oi < i)) {
+ v = ov;
+ i = oi;
+ }
+ }
+ const int warp = threadIdx.x >> 5;
+ if ((threadIdx.x & 31) == 0) {
+ red_v[warp] = v;
+ red_i[warp] = i;
+ }
+ __syncthreads();
+ v = red_v[0];
+ i = red_i[0];
+ for (int w = 1; w < SAMPLE_CHILDREN_THREADS / 32; ++w) {
+ if (red_v[w] > v || (red_v[w] == v && red_i[w] < i)) {
+ v = red_v[w];
+ i = red_i[w];
+ }
+ }
+ __syncthreads();
+}
+
+__device__ __forceinline__ float block_sum_128(float v, float* red) {
+ for (int offset = 16; offset > 0; offset >>= 1) v += __shfl_xor_sync(0xffffffff, v, offset);
+ const int warp = threadIdx.x >> 5;
+ if ((threadIdx.x & 31) == 0) red[warp] = v;
+ __syncthreads();
+ float total = 0.0f;
+ for (int w = 0; w < SAMPLE_CHILDREN_THREADS / 32; ++w) total += red[w];
+ __syncthreads();
+ return total;
+}
+
+__global__ void sample_children_kernel(
+ const float* __restrict__ logits_base, int64_t logits_s0, int64_t logits_s1,
+ const int64_t* __restrict__ cand_base, int64_t cand_s0, int64_t cand_s1,
+ int64_t* __restrict__ tokens_base, int64_t tokens_s0, int64_t tokens_s1,
+ float* __restrict__ scores_base, int64_t scores_s0, int64_t scores_s1,
+ const float* __restrict__ temps, const int32_t* __restrict__ top_ks,
+ const float* __restrict__ top_ps, float* __restrict__ q_store, int32_t* __restrict__ qid_store,
+ int32_t* __restrict__ node_slot, int32_t* __restrict__ node_pos, int rows_per_req,
+ const int* __restrict__ width_ptr, int slot_base, const int* __restrict__ cumu_start_ptr,
+ int num_slots, int max_nodes, int nc, int k, int64_t vocab_limit, uint64_t seed,
+ const int64_t* __restrict__ round_counter, int launch) {
+ // Request b's row w of its first `width` rows, expanded row m = b * width + w in the draws.
+ const int b = blockIdx.x / rows_per_req;
+ const int w = blockIdx.x - b * rows_per_req;
+ const int width = width_ptr == nullptr ? rows_per_req : *width_ptr;
+ if (w >= width) return;
+ const int m = b * width + w;
+ const int cumu_start = *cumu_start_ptr;
+ const float* logits = logits_base + b * logits_s0 + w * logits_s1;
+ const int64_t* cand = cand_base + b * cand_s0 + w * cand_s1;
+ int64_t* tokens = tokens_base + b * tokens_s0 + w * tokens_s1;
+ float* scores = scores_base + b * scores_s0 + w * scores_s1;
+ const int tid = threadIdx.x;
+ const int64_t node_row = (int64_t)b * max_nodes + cumu_start + (int64_t)w * k;
+ const float temp = temps[b];
+ if (temp <= 0.0f) {
+ if (tid < k) node_slot[node_row + tid] = -1;
+ return;
+ }
+ __shared__ float red_v[SAMPLE_CHILDREN_THREADS / 32];
+ __shared__ int red_i[SAMPLE_CHILDREN_THREADS / 32];
+ const float inv_temp = 1.0f / temp;
+ float x[SAMPLE_CHILDREN_PER_THREAD];
+ float x_max = -FLT_MAX;
+#pragma unroll
+ for (int t = 0; t < SAMPLE_CHILDREN_PER_THREAD; ++t) {
+ const int j = tid + t * SAMPLE_CHILDREN_THREADS;
+ const bool valid = j < nc && cand[j] < vocab_limit;
+ x[t] = valid ? logits[j] * inv_temp : -FLT_MAX;
+ x_max = fmaxf(x_max, x[t]);
+ }
+ int dummy = 0;
+ block_argmax_128(x_max, dummy, red_v, red_i);
+ float e_sum = 0.0f;
+#pragma unroll
+ for (int t = 0; t < SAMPLE_CHILDREN_PER_THREAD; ++t) {
+ const int j = tid + t * SAMPLE_CHILDREN_THREADS;
+ x[t] = (j < nc && x[t] > -FLT_MAX) ? __expf(x[t] - x_max) : 0.0f;
+ e_sum += x[t];
+ }
+ float inv_sum = 1.0f / block_sum_128(e_sum, red_v);
+ const int top_k = top_ks[b];
+ const float top_p = top_ps[b];
+ if (top_k < nc || top_p < 1.0f) {
+ __shared__ float s_q[SAMPLE_CHILDREN_THREADS * SAMPLE_CHILDREN_PER_THREAD];
+#pragma unroll
+ for (int t = 0; t < SAMPLE_CHILDREN_PER_THREAD; ++t) {
+ const int j = tid + t * SAMPLE_CHILDREN_THREADS;
+ if (j < nc) s_q[j] = x[t] * inv_sum;
+ }
+ __syncthreads();
+ float kept_sum = 0.0f;
+#pragma unroll
+ for (int t = 0; t < SAMPLE_CHILDREN_PER_THREAD; ++t) {
+ const int j = tid + t * SAMPLE_CHILDREN_THREADS;
+ if (j >= nc || x[t] <= 0.0f) continue;
+ const float q_j = s_q[j];
+ int above = 0;
+ float mass_above = 0.0f;
+ for (int i = 0; i < nc; ++i) {
+ const float q_i = s_q[i];
+ if (q_i > q_j) {
+ ++above;
+ mass_above += q_i;
+ }
+ }
+ if (above < top_k && mass_above < top_p)
+ kept_sum += x[t];
+ else
+ x[t] = 0.0f;
+ }
+ inv_sum = 1.0f / block_sum_128(kept_sum, red_v);
+ }
+ const int s = slot_base + w;
+ const int64_t store_row = ((int64_t)b * num_slots + s) * nc;
+ const uint64_t stream = static_cast<uint64_t>(round_counter[0]) * 64 + launch;
+ float key[SAMPLE_CHILDREN_PER_THREAD];
+#pragma unroll
+ for (int t = 0; t < SAMPLE_CHILDREN_PER_THREAD; ++t) {
+ const int j = tid + t * SAMPLE_CHILDREN_THREADS;
+ if (j < nc) {
+ const float q = x[t] * inv_sum;
+ q_store[store_row + j] = q;
+ qid_store[store_row + j] = static_cast<int32_t>(cand[j]);
+ curandStatePhilox4_32_10_t state;
+ curand_init(seed, (stream << 20) | ((uint64_t)m << 10) | (uint64_t)j, 0, &state);
+ const double u = ((double)curand(&state) + 0.5) * 2.3283064365386963e-10;
+ key[t] = q > 0.0f ? (float)((double)logf(q) - log(-log(u)))
+ : (cand[j] < vocab_limit ? -1e30f : -2e30f);
+ } else {
+ key[t] = -FLT_MAX;
+ }
+ }
+ for (int i = 0; i < k; ++i) {
+ float best_v = -FLT_MAX;
+ int best_j = nc;
+#pragma unroll
+ for (int t = 0; t < SAMPLE_CHILDREN_PER_THREAD; ++t) {
+ const int j = tid + t * SAMPLE_CHILDREN_THREADS;
+ if (j < nc && (key[t] > best_v || (key[t] == best_v && j < best_j))) {
+ best_v = key[t];
+ best_j = j;
+ }
+ }
+ block_argmax_128(best_v, best_j, red_v, red_i);
+#pragma unroll
+ for (int t = 0; t < SAMPLE_CHILDREN_PER_THREAD; ++t) {
+ if (tid + t * SAMPLE_CHILDREN_THREADS == best_j) key[t] = -FLT_MAX;
+ }
+ if (tid == 0) {
+ tokens[i] = cand[best_j];
+ node_slot[node_row + i] = s;
+ node_pos[node_row + i] = best_j;
+ // A child past the cut's support can never be accepted.
+ if (best_v <= -1e29f) scores[i] = 0.0f;
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// The verify tree's acceptance by rejection sampling, one CTA per request and
+// one warp per node. A node's children (the nodes whose parent it is, in index
+// order) are tried in turn against the target's row p' at the node: sampled
+// children (their parent's q recorded) by recursive rejection without
+// replacement, which updates the row to the residual (p' - q)+ as children are
+// rejected; deterministic children by p'(child) over the mass left. The
+// accepted path runs from the root; the bonus token comes from the last
+// accepted node's residual row (residual_sample).
+//
+// A greedy row (top-k 1) has a one-hot p' at its argmax: rejection accepts the
+// first child holding the argmax for every coin and rejects the others, so the
+// kernel decides it from the argmax alone and never reads the row.
+// ---------------------------------------------------------------------------
+// The first child of `node` after node `after` (children in index order), -1 past the last.
+__device__ __forceinline__ int next_child(const int32_t* s_parent, int node, int after,
+ int num_nodes) {
+ for (int j = after + 1; j < num_nodes; ++j) {
+ if (s_parent[j] == node) return j;
+ }
+ return -1;
+}
+
+// torch.argmax's order: NaN first, then larger values, ties to the lower index.
+__device__ __forceinline__ bool argmax_before(float v, int i, float best_v, int best_i) {
+ if (isnan(v)) return !isnan(best_v) || i < best_i;
+ if (isnan(best_v)) return false;
+ return v > best_v || (v == best_v && i < best_i);
+}
+
+__global__ void tree_reject_sample_kernel(
+ float* __restrict__ probas, int64_t probas_stride, const int32_t* __restrict__ tokens,
+ const int32_t* __restrict__ parents, const int64_t* __restrict__ q_rows,
+ const int32_t* __restrict__ q_slot, const int32_t* __restrict__ q_pos,
+ const float* __restrict__ q_store, const int32_t* __restrict__ qid_store,
+ const float* __restrict__ coins, int64_t coins_stride, const int32_t* __restrict__ top_ks,
+ const int64_t* __restrict__ argmax, int32_t* __restrict__ path,
+ int32_t* __restrict__ predicts, int32_t* __restrict__ accept_length,
+ int64_t* __restrict__ last_row, int num_nodes, int num_slots, int nc, int vocab) {
+ const float PROBA_EPS = 1e-6f;
+ const float PROBA_OFFSET = 2e-6f;
+ const int b = blockIdx.x;
+ __shared__ int32_t s_parent[MAX_TREE_NODES];
+ __shared__ int s_accept_child[MAX_TREE_NODES];
+ for (int i = threadIdx.x; i < num_nodes; i += blockDim.x) {
+ s_parent[i] = parents[(int64_t)b * num_nodes + i];
+ }
+ __syncthreads();
+ const int lane = threadIdx.x & 31;
+ const int num_warps = blockDim.x >> 5;
+ const int64_t q_row = q_rows != nullptr ? q_rows[b] : -1;
+ for (int node = threadIdx.x >> 5; node < num_nodes; node += num_warps) {
+ const int64_t row = (int64_t)b * num_nodes + node;
+ float* p = probas + row * probas_stride;
+ int child = next_child(s_parent, node, node, num_nodes);
+ int accepted = -1;
+ const bool greedy = top_ks[row] == 1;
+ const int32_t slot =
+ (!greedy && q_row >= 0 && child >= 0) ? q_slot[q_row * num_nodes + child] : -1;
+ if (slot >= 0) {
+ const int64_t store_row = (q_row * num_slots + slot) * nc;
+ const float* q_row_ptr = q_store + store_row;
+ const int32_t* id_row = qid_store + store_row;
+ constexpr int MAX_SAMPLED_CHILDREN = 16;
+ int rejected_pos[MAX_SAMPLED_CHILDREN];
+ int rejected_count = 0;
+ float q_left = 0.0f, p_cand = 0.0f;
+ // The row's argmax before its updates, for a residual that vanishes:
+ // every entry of the row the updates below touch is folded in before
+ // its first one.
+ float best_v = -INFINITY;
+ int best_i = INT_MAX;
+ for (int j = lane; j < nc; j += 32) {
+ const float q_j = q_row_ptr[j];
+ if (q_j > 0.0f) {
+ q_left += q_j;
+ const int32_t token = id_row[j];
+ const float p_j = p[token];
+ p_cand += p_j;
+ if (static_cast<unsigned>(token) < static_cast<unsigned>(vocab) &&
+ argmax_before(p_j, token, best_v, best_i)) {
+ best_v = p_j;
+ best_i = token;
+ }
+ }
+ }
+ for (int offset = 16; offset > 0; offset >>= 1) {
+ q_left += __shfl_xor_sync(0xffffffff, q_left, offset);
+ p_cand += __shfl_xor_sync(0xffffffff, p_cand, offset);
+ }
+ const float z_out = fmaxf(1.0f - p_cand, 0.0f);
+ float z = 1.0f;
+ while (child >= 0) {
+ const int pos = q_pos[q_row * num_nodes + child];
+ const int64_t child_token = tokens[(int64_t)b * num_nodes + child];
+ const float q_child = q_row_ptr[pos];
+ if (q_child > 0.0f && q_left > 0.0f && z > 0.0f) {
+ const float q_i = q_child / q_left;
+ const float r_child = p[child_token];
+ if (static_cast<uint64_t>(child_token) < static_cast<uint64_t>(vocab) &&
+ argmax_before(r_child, static_cast<int>(child_token), best_v, best_i)) {
+ best_v = r_child;
+ best_i = static_cast<int>(child_token);
+ }
+ if (coins[(int64_t)b * coins_stride + child] * q_i * z < r_child) {
+ accepted = child;
+ break;
+ }
+ const float scale = z / q_left;
+ float r_sum = 0.0f, q_sum = 0.0f;
+ for (int j = lane; j < nc; j += 32) {
+ const float q_j = q_row_ptr[j];
+ if (q_j <= 0.0f || j == pos) continue;
+ const int32_t token = id_row[j];
+ bool gone = false;
+ for (int r = 0; r < rejected_count; ++r) gone |= (rejected_pos[r] == j);
+ if (gone) {
+ r_sum += p[token];
+ continue;
+ }
+ const float r_new = fmaxf(p[token] - scale * q_j, 0.0f);
+ p[token] = r_new;
+ r_sum += r_new;
+ q_sum += q_j;
+ }
+ for (int offset = 16; offset > 0; offset >>= 1) {
+ r_sum += __shfl_xor_sync(0xffffffff, r_sum, offset);
+ q_sum += __shfl_xor_sync(0xffffffff, q_sum, offset);
+ }
+ const float r_y = fmaxf(r_child - scale * q_child, 0.0f);
+ if (lane == 0) p[child_token] = r_y;
+ __syncwarp();
+ const float z_new = z_out + r_sum + r_y;
+ if (!(z_new > 1e-6f * z)) {
+ if (r_child > 0.0f) {
+ accepted = child;
+ } else {
+ // The bonus is the target's argmax: the entries not updated
+ // above still hold their target values (rare, so scanned here).
+ for (int j = lane; j < vocab; j += 32) {
+ const float v = p[j];
+ if (argmax_before(v, j, best_v, best_i)) {
+ best_v = v;
+ best_i = j;
+ }
+ }
+ for (int offset = 16; offset > 0; offset >>= 1) {
+ const float other_v = __shfl_xor_sync(0xffffffff, best_v, offset);
+ const int other_i = __shfl_xor_sync(0xffffffff, best_i, offset);
+ if (argmax_before(other_v, other_i, best_v, best_i)) {
+ best_v = other_v;
+ best_i = other_i;
+ }
+ }
+ if (lane == 0) p[best_i] = 1.0f;
+ __syncwarp();
+ }
+ break;
+ }
+ z = z_new;
+ q_left = q_sum;
+ if (rejected_count < MAX_SAMPLED_CHILDREN) rejected_pos[rejected_count++] = pos;
+ }
+ child = next_child(s_parent, node, child, num_nodes);
+ }
+ } else if (lane == 0 && greedy) {
+ const int64_t best = argmax[row];
+ while (child >= 0 && tokens[(int64_t)b * num_nodes + child] != best) {
+ child = next_child(s_parent, node, child, num_nodes);
+ }
+ accepted = child;
+ } else if (lane == 0) {
+ float total = 1.0f;
+ while (child >= 0) {
+ const int64_t child_token = tokens[(int64_t)b * num_nodes + child];
+ const float child_proba = p[child_token];
+ const float coin = coins[(int64_t)b * coins_stride + child];
+ if (child_proba > 0.0f && coin <= (child_proba + PROBA_OFFSET) / (total + PROBA_EPS)) {
+ accepted = child;
+ break;
+ }
+ total = fmaxf(total - child_proba, 0.0f);
+ p[child_token] = 0.0f;
+ child = next_child(s_parent, node, child, num_nodes);
+ }
+ }
+ if (lane == 0) s_accept_child[node] = accepted;
+ }
+ __syncthreads();
+ if (threadIdx.x == 0) {
+ int32_t* path_b = path + (int64_t)b * num_nodes;
+ int32_t* predicts_b = predicts + (int64_t)b * num_nodes;
+ int length = 1;
+ int node = 0;
+ path_b[0] = 0;
+ for (int c = s_accept_child[0]; c >= 0; c = s_accept_child[node]) {
+ predicts_b[length - 1] = tokens[(int64_t)b * num_nodes + c];
+ path_b[length++] = c;
+ node = c;
+ }
+ for (int i = length; i < num_nodes; ++i) path_b[i] = -1;
+ accept_length[b] = length;
+ last_row[b] = (int64_t)b * num_nodes + node;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// The bonus token: an inverse-CDF draw from the last accepted node's (residual)
+// row with the request's final coin; the row need not be normalized. Written
+// at the end of the accepted path in ``predicts``. A greedy row's residual is
+// its one-hot p' (its argmax child, if any, was accepted): the bonus is its
+// argmax, the row unread.
+// ---------------------------------------------------------------------------
+constexpr int RESIDUAL_SAMPLE_THREADS = 1024;
+// Each warp stages its 32 lanes' segments through shared memory in runs of 16
+// elements, so the global loads stay coalesced; every lane still sums its own
+// segment left to right.
+constexpr int RESIDUAL_SAMPLE_RUN = 16;
+static_assert(32 % RESIDUAL_SAMPLE_RUN == 0, "a warp load stages whole runs");
+constexpr int RESIDUAL_SAMPLE_SMEM_BYTES =
+ RESIDUAL_SAMPLE_THREADS * (RESIDUAL_SAMPLE_RUN + 1) * sizeof(float);
+
+__global__ void __launch_bounds__(RESIDUAL_SAMPLE_THREADS)
+ residual_sample_kernel(const float* __restrict__ probas, int64_t probas_stride,
+ const int64_t* __restrict__ last_row, const float* __restrict__ coins,
+ const int32_t* __restrict__ top_ks,
+ const int64_t* __restrict__ argmax,
+ const int32_t* __restrict__ accept_length,
+ int32_t* __restrict__ predicts, int num_nodes, int vocab) {
+ const int b = blockIdx.x;
+ const int64_t row = last_row[b];
+ if (top_ks[row] == 1) {
+ if (threadIdx.x == 0) {
+ predicts[(int64_t)b * num_nodes + accept_length[b] - 1] = static_cast<int32_t>(argmax[row]);
+ }
+ return;
+ }
+ const float* p = probas + row * probas_stride;
+ const int seg = (vocab + RESIDUAL_SAMPLE_THREADS - 1) / RESIDUAL_SAMPLE_THREADS;
+ const int start = min(threadIdx.x * seg, vocab);
+ const int end = min(start + seg, vocab);
+ const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
+ extern __shared__ float s_runs[];
+ // Row r of this warp's [32, RUN + 1] tile holds a run of lane r's segment.
+ float* runs = s_runs + warp * 32 * (RESIDUAL_SAMPLE_RUN + 1);
+ // A warp load stages 32 / RUN runs: lane l fills column l % RUN of run l / RUN.
+ const int col = lane % RESIDUAL_SAMPLE_RUN;
+ float local = 0.0f;
+ int last_positive = -1;
+ for (int c = 0; c < seg; c += RESIDUAL_SAMPLE_RUN) {
+#pragma unroll
+ for (int r0 = 0; r0 < 32; r0 += 32 / RESIDUAL_SAMPLE_RUN) {
+ const int r = r0 + lane / RESIDUAL_SAMPLE_RUN;
+ const int r_start = min((warp * 32 + r) * seg, vocab);
+ const int i = r_start + c + col;
+ runs[r * (RESIDUAL_SAMPLE_RUN + 1) + col] =
+ i < min(r_start + seg, vocab) ? p[i] : 0.0f;
+ }
+ __syncwarp();
+ const int n = min(RESIDUAL_SAMPLE_RUN, end - start - c);
+ for (int j = 0; j < n; ++j) {
+ const float v = runs[lane * (RESIDUAL_SAMPLE_RUN + 1) + j];
+ local += v;
+ if (v > 0.0f) last_positive = start + c + j;
+ }
+ __syncwarp();
+ }
+ // Inclusive scan of the segment sums over the block.
+ __shared__ float s_warp[RESIDUAL_SAMPLE_THREADS / 32];
+ __shared__ int s_last[RESIDUAL_SAMPLE_THREADS / 32];
+ __shared__ int s_token;
+ float incl = local;
+ int last = last_positive;
+ for (int offset = 1; offset < 32; offset <<= 1) {
+ const float u = __shfl_up_sync(0xffffffff, incl, offset);
+ if (lane >= offset) incl += u;
+ }
+ for (int offset = 16; offset > 0; offset >>= 1) last = max(last, __shfl_xor_sync(0xffffffff, last, offset));
+ if (lane == 31) s_warp[warp] = incl;
+ if (lane == 0) s_last[warp] = last;
+ if (threadIdx.x == 0) s_token = INT_MAX;
+ __syncthreads();
+ float before = 0.0f, total = 0.0f;
+ int any_last = -1;
+ for (int w = 0; w < RESIDUAL_SAMPLE_THREADS / 32; ++w) {
+ if (w < warp) before += s_warp[w];
+ total += s_warp[w];
+ any_last = max(any_last, s_last[w]);
+ }
+ const float exclusive = before + incl - local;
+ const float target = coins[b] * total;
+ // A claiming lane rescans its segment, staged run by run through its warp's tile.
+ const bool claim = local > 0.0f && exclusive <= target && target < exclusive + local;
+ for (unsigned claims = __ballot_sync(0xffffffff, claim); claims != 0; claims &= claims - 1) {
+ const int r = __ffs(claims) - 1;
+ const int r_start = __shfl_sync(0xffffffff, start, r);
+ const int r_end = __shfl_sync(0xffffffff, end, r);
+ float acc = exclusive;
+ for (int c = r_start; c < r_end; c += RESIDUAL_SAMPLE_RUN) {
+ if (lane < RESIDUAL_SAMPLE_RUN) runs[lane] = c + lane < r_end ? p[c + lane] : 0.0f;
+ __syncwarp();
+ int token = -1;
+ if (lane == r) {
+ const int n = min(RESIDUAL_SAMPLE_RUN, r_end - c);
+ for (int j = 0; j < n; ++j) {
+ acc += runs[j];
+ if (acc > target && runs[j] > 0.0f) {
+ token = c + j;
+ break;
+ }
+ }
+ }
+ token = __shfl_sync(0xffffffff, token, r);
+ __syncwarp();
+ if (token >= 0) {
+ // Rounding can make neighbouring segments overlap: the lowest claim wins.
+ if (lane == 0) atomicMin(&s_token, token);
+ break;
+ }
+ }
+ }
+ __syncthreads();
+ if (threadIdx.x == 0) {
+ // Rounding can also leave the target in a gap, or at the very end of the mass.
+ const int token = s_token != INT_MAX ? s_token : max(any_last, 0);
+ predicts[(int64_t)b * num_nodes + accept_length[b] - 1] = token;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// A sampled round's draft distributions into the next round's tables, at the
+// request's row: its slots' q and candidate ids, and per verify node the slot
+// and position of its parent's draw (-1: the root, a deterministic child, or a
+// slot past verify_num).
+// ---------------------------------------------------------------------------
+__global__ void publish_draft_q_kernel(const int64_t* __restrict__ ranked, int64_t ranked_stride,
+ const int32_t* __restrict__ node_slot,
+ const int32_t* __restrict__ node_pos, int64_t node_stride,
+ const float* __restrict__ q_round,
+ const int32_t* __restrict__ qid_round,
+ const int64_t* __restrict__ rows, float* __restrict__ q_tab,
+ int32_t* __restrict__ qid_tab, int32_t* __restrict__ slot_tab,
+ int32_t* __restrict__ pos_tab,
+ const int* __restrict__ live_rows,
+ const int* __restrict__ verify_num_ptr, int num_nodes,
+ int64_t store_size) {
+ const int b = blockIdx.x;
+ if (b >= *live_rows) return;
+ const int verify_num = *verify_num_ptr;
+ const int64_t row = rows[b];
+ for (int i = threadIdx.x; i < num_nodes; i += blockDim.x) {
+ int32_t slot = -1, pos = 0;
+ if (i > 0 && i < verify_num) {
+ const int64_t node = ranked[(int64_t)b * ranked_stride + i];
+ slot = node_slot[(int64_t)b * node_stride + node];
+ pos = node_pos[(int64_t)b * node_stride + node];
+ }
+ slot_tab[row * num_nodes + i] = slot;
+ pos_tab[row * num_nodes + i] = pos;
+ }
+ for (int64_t i = threadIdx.x; i < store_size; i += blockDim.x) {
+ q_tab[row * store_size + i] = q_round[(int64_t)b * store_size + i];
+ qid_tab[row * store_size + i] = qid_round[(int64_t)b * store_size + i];
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Host entry points: shapes and strides are checked, dtypes are the caller's.
+// ---------------------------------------------------------------------------
+void eagle_harness_sample_children(TensorView logits, TensorView cand, TensorView tokens,
+ TensorView scores, TensorView temps, TensorView top_ks,
+ TensorView top_ps, TensorView q_store, TensorView qid_store,
+ TensorView node_slot, TensorView node_pos,
+ Optional<TensorView> width, int64_t slot_base,
+ TensorView cumu_start, int64_t vocab_limit, int64_t seed,
+ TensorView round_counter, int64_t launch) {
+ TVM_FFI_ICHECK(logits.ndim() == 3 && cand.ndim() == 3 && tokens.ndim() == 3 &&
+ scores.ndim() == 3 && logits.stride(2) == 1 && cand.stride(2) == 1 &&
+ tokens.stride(2) == 1 && scores.stride(2) == 1)
+ << "eagle_harness_sample_children: [requests, rows, *] views";
+ const int nc = static_cast<int>(q_store.size(2));
+ const int64_t requests = tokens.size(0);
+ const int64_t rows_per_req = tokens.size(1);
+ const int k = static_cast<int>(tokens.size(2));
+ const int64_t rows = requests * rows_per_req;
+ TVM_FFI_ICHECK(logits.size(2) == nc && cand.size(2) == nc && qid_store.size(2) == nc)
+ << "eagle_harness_sample_children: candidate width";
+ TVM_FFI_ICHECK(logits.size(0) == requests && cand.size(0) == requests &&
+ scores.size(0) == requests && logits.size(1) == rows_per_req &&
+ cand.size(1) == rows_per_req && scores.size(1) == rows_per_req &&
+ scores.size(2) == k)
+ << "eagle_harness_sample_children: expanded rows";
+ TVM_FFI_ICHECK(node_slot.size(1) == node_pos.size(1) &&
+ node_slot.stride(0) == node_pos.stride(0) && node_pos.stride(1) == 1)
+ << "eagle_harness_sample_children: node tables";
+ // The caller keeps cumu_start + width * K within the node tables.
+ TVM_FFI_ICHECK(rows_per_req > 0 && slot_base + rows_per_req <= q_store.size(1))
+ << "eagle_harness_sample_children: slot range";
+ TVM_FFI_ICHECK(nc <= SAMPLE_CHILDREN_THREADS * SAMPLE_CHILDREN_PER_THREAD && rows <= 1024 &&
+ launch >= 0 && launch < 64)
+ << "eagle_harness_sample_children: counter layout";
+ if (rows == 0) return;
+ sample_children_kernel<<<rows, SAMPLE_CHILDREN_THREADS, 0, get_stream(logits.device())>>>(
+ static_cast<const float*>(logits.data_ptr()), logits.stride(0), logits.stride(1),
+ static_cast<const int64_t*>(cand.data_ptr()), cand.stride(0), cand.stride(1),
+ static_cast<int64_t*>(tokens.data_ptr()), tokens.stride(0), tokens.stride(1),
+ static_cast<float*>(scores.data_ptr()), scores.stride(0), scores.stride(1),
+ static_cast<const float*>(temps.data_ptr()), static_cast<const int32_t*>(top_ks.data_ptr()),
+ static_cast<const float*>(top_ps.data_ptr()), static_cast<float*>(q_store.data_ptr()),
+ static_cast<int32_t*>(qid_store.data_ptr()), static_cast<int32_t*>(node_slot.data_ptr()),
+ static_cast<int32_t*>(node_pos.data_ptr()), static_cast<int>(rows_per_req),
+ width.has_value() ? static_cast<const int*>(width.value().data_ptr()) : nullptr,
+ static_cast<int>(slot_base), static_cast<const int*>(cumu_start.data_ptr()),
+ static_cast<int>(q_store.size(1)),
+ static_cast<int>(node_slot.size(1)), nc, k, vocab_limit,
+ static_cast<uint64_t>(seed), static_cast<const int64_t*>(round_counter.data_ptr()),
+ static_cast<int>(launch));
+}
+
+void eagle_harness_tree_reject_sample(TensorView probas, TensorView tokens, TensorView parents,
+ Optional<TensorView> q_rows, TensorView q_slot,
+ TensorView q_pos, TensorView q_store, TensorView qid_store,
+ TensorView coins, TensorView top_ks, TensorView argmax,
+ TensorView path, TensorView predicts,
+ TensorView accept_length, TensorView last_row) {
+ TVM_FFI_ICHECK(probas.stride(1) == 1 && coins.stride(1) == 1);
+ const int batch_size = static_cast<int>(tokens.size(0));
+ const int num_nodes = static_cast<int>(tokens.size(1));
+ TVM_FFI_ICHECK_LE(num_nodes, MAX_TREE_NODES);
+ // The kernel indexes the trees and their q tables with the trees' row width.
+ TVM_FFI_ICHECK(tokens.stride(0) == num_nodes && parents.size(1) == num_nodes &&
+ parents.stride(0) == num_nodes && coins.size(1) >= num_nodes &&
+ probas.size(0) >= static_cast<int64_t>(batch_size) * num_nodes)
+ << "eagle_harness_tree_reject_sample: row widths";
+ TVM_FFI_ICHECK(top_ks.ndim() == 1 && top_ks.stride(0) == 1 && argmax.ndim() == 1 &&
+ argmax.stride(0) == 1 &&
+ top_ks.size(0) >= static_cast<int64_t>(batch_size) * num_nodes &&
+ argmax.size(0) >= static_cast<int64_t>(batch_size) * num_nodes)
+ << "eagle_harness_tree_reject_sample: one top-k and argmax per row";
+ if (q_rows.has_value()) {
+ TVM_FFI_ICHECK(q_slot.size(1) == num_nodes && q_pos.size(1) == num_nodes &&
+ q_slot.stride(0) == num_nodes && q_pos.stride(0) == num_nodes)
+ << "eagle_harness_tree_reject_sample: q table row widths";
+ }
+ if (batch_size == 0) return;
+ const bool sampled = q_rows.has_value();
+ const int threads = std::min(1024, 32 * num_nodes);
+ tree_reject_sample_kernel<<<batch_size, threads, 0, get_stream(probas.device())>>>(
+ static_cast<float*>(probas.data_ptr()), probas.stride(0),
+ static_cast<const int32_t*>(tokens.data_ptr()), static_cast<const int32_t*>(parents.data_ptr()),
+ sampled ? static_cast<const int64_t*>(q_rows.value().data_ptr()) : nullptr,
+ static_cast<const int32_t*>(q_slot.data_ptr()), static_cast<const int32_t*>(q_pos.data_ptr()),
+ static_cast<const float*>(q_store.data_ptr()),
+ static_cast<const int32_t*>(qid_store.data_ptr()), static_cast<const float*>(coins.data_ptr()),
+ coins.stride(0), static_cast<const int32_t*>(top_ks.data_ptr()),
+ static_cast<const int64_t*>(argmax.data_ptr()), static_cast<int32_t*>(path.data_ptr()),
+ static_cast<int32_t*>(predicts.data_ptr()), static_cast<int32_t*>(accept_length.data_ptr()),
+ static_cast<int64_t*>(last_row.data_ptr()), num_nodes, static_cast<int>(q_store.size(1)),
+ static_cast<int>(q_store.size(2)), static_cast<int>(probas.size(1)));
+}
+
+void eagle_harness_residual_sample(TensorView probas, TensorView last_row, TensorView coins,
+ TensorView top_ks, TensorView argmax, TensorView accept_length,
+ TensorView predicts, int64_t num_nodes) {
+ TVM_FFI_ICHECK_EQ(probas.stride(1), 1);
+ const int batch_size = static_cast<int>(last_row.size(0));
+ TVM_FFI_ICHECK(predicts.size(0) >= batch_size * num_nodes && accept_length.size(0) >= batch_size)
+ << "eagle_harness_residual_sample: output rows";
+ // last_row indexes probas rows, and so the per-row top-k and argmax.
+ TVM_FFI_ICHECK(top_ks.ndim() == 1 && top_ks.stride(0) == 1 && argmax.ndim() == 1 &&
+ argmax.stride(0) == 1 && top_ks.size(0) >= probas.size(0) &&
+ argmax.size(0) >= probas.size(0))
+ << "eagle_harness_residual_sample: one top-k and argmax per row";
+ if (batch_size == 0) return;
+ const cudaError_t smem_status = cudaFuncSetAttribute(
+ residual_sample_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize,
+ RESIDUAL_SAMPLE_SMEM_BYTES);
+ TVM_FFI_ICHECK(smem_status == cudaSuccess)
+ << "eagle_harness_residual_sample: " << cudaGetErrorString(smem_status);
+ residual_sample_kernel<<<batch_size, RESIDUAL_SAMPLE_THREADS, RESIDUAL_SAMPLE_SMEM_BYTES,
+ get_stream(probas.device())>>>(
+ static_cast<const float*>(probas.data_ptr()), probas.stride(0),
+ static_cast<const int64_t*>(last_row.data_ptr()), static_cast<const float*>(coins.data_ptr()),
+ static_cast<const int32_t*>(top_ks.data_ptr()), static_cast<const int64_t*>(argmax.data_ptr()),
+ static_cast<const int32_t*>(accept_length.data_ptr()),
+ static_cast<int32_t*>(predicts.data_ptr()), static_cast<int>(num_nodes),
+ static_cast<int>(probas.size(1)));
+}
+
+void eagle_harness_publish_draft_q(TensorView ranked, TensorView node_slot, TensorView node_pos,
+ TensorView q_round, TensorView qid_round, TensorView rows,
+ TensorView q_tab, TensorView qid_tab, TensorView slot_tab,
+ TensorView pos_tab, TensorView live_rows,
+ TensorView verify_num) {
+ TVM_FFI_ICHECK(ranked.stride(1) == 1 && node_slot.stride(1) == 1);
+ TVM_FFI_ICHECK_EQ(node_slot.stride(0), node_pos.stride(0));
+ // The caller keeps verify_num within the ranked columns and the table slots.
+ TVM_FFI_ICHECK(slot_tab.size(1) == pos_tab.size(1))
+ << "eagle_harness_publish_draft_q: node tables";
+ const int batch_size = static_cast<int>(ranked.size(0));
+ const int64_t store_size = q_round.size(1) * q_round.size(2);
+ TVM_FFI_ICHECK_EQ(q_tab.size(1) * q_tab.size(2), store_size);
+ if (batch_size == 0) return;
+ publish_draft_q_kernel<<<batch_size, 256, 0, get_stream(ranked.device())>>>(
+ static_cast<const int64_t*>(ranked.data_ptr()), ranked.stride(0),
+ static_cast<const int32_t*>(node_slot.data_ptr()),
+ static_cast<const int32_t*>(node_pos.data_ptr()), node_slot.stride(0),
+ static_cast<const float*>(q_round.data_ptr()), static_cast<const int32_t*>(qid_round.data_ptr()),
+ static_cast<const int64_t*>(rows.data_ptr()), static_cast<float*>(q_tab.data_ptr()),
+ static_cast<int32_t*>(qid_tab.data_ptr()), static_cast<int32_t*>(slot_tab.data_ptr()),
+ static_cast<int32_t*>(pos_tab.data_ptr()), static_cast<const int*>(live_rows.data_ptr()),
+ static_cast<const int*>(verify_num.data_ptr()), static_cast<int>(slot_tab.size(1)),
+ store_size);
+}
+
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(eagle_harness_update_node_data, eagle_harness_update_node_data);
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(eagle_harness_write_verify_tree, eagle_harness_write_verify_tree);
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(eagle_harness_work_deltas, eagle_harness_work_deltas);
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(eagle_harness_draft_depth_update, eagle_harness_draft_depth_update);
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(eagle_harness_stable_topk_desc, eagle_harness_stable_topk_desc);
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(eagle_harness_sample_children, eagle_harness_sample_children);
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(eagle_harness_tree_reject_sample, eagle_harness_tree_reject_sample);
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(eagle_harness_residual_sample, eagle_harness_residual_sample);
+TVM_FFI_DLL_EXPORT_TYPED_FUNC(eagle_harness_publish_draft_q, eagle_harness_publish_draft_q);
diff --git a/eagle_harness/tokenspeed/tree_round/ops/csrc/tvm_ffi_utils.h b/eagle_harness/tokenspeed/tree_round/ops/csrc/tvm_ffi_utils.h
new file mode 100644
index 0000000..28cc0aa
--- /dev/null
+++ b/eagle_harness/tokenspeed/tree_round/ops/csrc/tvm_ffi_utils.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2023 by FlashInfer team.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+// Modified by Eagle AI Corp.
+
+#pragma once
+#include <cuda_runtime.h>
+#include <tvm/ffi/container/tensor.h>
+#include <tvm/ffi/dtype.h>
+#include <tvm/ffi/error.h>
+#include <tvm/ffi/extra/c_env_api.h>
+#include <tvm/ffi/function.h>
+#include <dlpack/dlpack.h>
+using tvm::ffi::TensorView;
+constexpr DLDataType dl_int32 = DLDataType{kDLInt, 32, 1};
+constexpr DLDataType dl_int64 = DLDataType{kDLInt, 64, 1};
+constexpr DLDataType dl_float32 = DLDataType{kDLFloat, 32, 1};
+constexpr DLDataType dl_float64 = DLDataType{kDLFloat, 64, 1};
+constexpr DLDataType dl_bool = DLDataType{kDLBool, 8, 1};
+
+inline cudaStream_t get_stream(DLDevice device) {
+ return static_cast<cudaStream_t>(TVMFFIEnvGetStream(device.device_type, device.device_id));
+}
+
+inline int64_t get_element_size(TensorView x) { return (x.dtype().bits * x.dtype().lanes) / 8; }
+
+inline void check_tensor(const TensorView& t, DLDataType dtype, DLDevice device) {
+ TVM_FFI_ICHECK(t.dtype() == dtype && t.device().device_type == kDLCUDA &&
+ t.device().device_id == device.device_id)
+ << "EAGLE-Harness: tensor dtype/device mismatch";
+}
+
+inline void check_scalar(const TensorView& t, DLDataType dtype, DLDevice device) {
+ check_tensor(t, dtype, device);
+ TVM_FFI_ICHECK(t.numel() == 1 && t.IsContiguous()) << "EAGLE-Harness: expected one device scalar";
+}
diff --git a/eagle_harness/tokenspeed/tree_round/ops/policy.py b/eagle_harness/tokenspeed/tree_round/ops/policy.py
new file mode 100644
index 0000000..9dbc748
--- /dev/null
+++ b/eagle_harness/tokenspeed/tree_round/ops/policy.py
@@ -0,0 +1,182 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""EAGLE-Harness device policy kernels (EAGLE-4); see
+``csrc/eagle_harness_policy.cu`` for the state and slot layouts, and the
+runtime's ``tree_round/device_policy.py`` for the tables and call order.
+
+Every kernel is one CTA reading its sizes from device memory, so each launch
+can be captured in a CUDA graph once and replayed for any round. Tables and
+state are contiguous CUDA tensors; ``frontier`` and the rows of
+``top_scores`` may be strided."""
+
+import torch
+
+from eagle_harness.tokenspeed.tree_round.ops.build import load_module
+
+__all__ = [
+ "eagle_harness_policy_begin_round",
+ "eagle_harness_policy_decide_chain",
+ "eagle_harness_policy_decide_tree",
+ "eagle_harness_policy_load",
+ "eagle_harness_policy_select_verify",
+ "eagle_harness_ranked_scores",
+]
+
+
+def eagle_harness_policy_load() -> None:
+ """Load the kernel library (no launch), before a graph capture uses it."""
+ load_module("policy")
+
+
+def eagle_harness_policy_begin_round(
+ state: torch.Tensor,
+ seq: torch.Tensor,
+ hist: torch.Tensor,
+ slots: torch.Tensor,
+ go_host: torch.Tensor,
+ batch_table: torch.Tensor,
+ tier_table: torch.Tensor,
+ cost_f64: torch.Tensor,
+ round_f64: torch.Tensor,
+ live_rows: torch.Tensor,
+ frontier: torch.Tensor,
+ sampled: torch.Tensor,
+ chain: bool,
+ node_top_k: int,
+ chain_past_verify_num: int,
+ verify_num: int,
+ min_verify_count: int,
+) -> None:
+ """Begin a serving tree or chain round on the current CUDA stream.
+
+ State and slot layouts match device_policy.py. Sampled rounds fix their
+ depth before proposals. Invalid live counts trap before any frontier read.
+ """
+ load_module("policy").eagle_harness_policy_begin_round(
+ state,
+ seq,
+ hist,
+ slots,
+ go_host,
+ batch_table,
+ tier_table,
+ cost_f64,
+ round_f64,
+ live_rows,
+ frontier,
+ sampled,
+ chain,
+ node_top_k,
+ chain_past_verify_num,
+ verify_num,
+ min_verify_count,
+ )
+
+
+def eagle_harness_policy_decide_tree(
+ state: torch.Tensor,
+ seq: torch.Tensor,
+ slots: torch.Tensor,
+ go_host: torch.Tensor,
+ work_deltas: torch.Tensor,
+ round_f64: torch.Tensor,
+ tier_table: torch.Tensor,
+ depth: int,
+ node_top_k: int,
+ exec_mode: int,
+ async_layer_ratio: float,
+ verify_num: int,
+ min_verify_count: int,
+) -> None:
+ """Decide tree width/depth using device counts; exec_mode must be zero.
+
+ A stop writes verify_count capped by the fixed verify width and pool size.
+ """
+ load_module("policy").eagle_harness_policy_decide_tree(
+ state,
+ seq,
+ slots,
+ go_host,
+ work_deltas,
+ round_f64,
+ tier_table,
+ depth,
+ node_top_k,
+ exec_mode,
+ async_layer_ratio,
+ verify_num,
+ min_verify_count,
+ )
+
+
+def eagle_harness_policy_decide_chain(
+ state: torch.Tensor,
+ seq: torch.Tensor,
+ slots: torch.Tensor,
+ go_host: torch.Tensor,
+ work_deltas: torch.Tensor,
+ round_f64: torch.Tensor,
+ depth: int,
+ verify_num: int,
+) -> None:
+ """A chain round's decision after ``depth``, as
+ ``eagle_harness_policy_decide_tree`` on contiguous fp32 ``[2]`` work
+ deltas, with the round's stop terms per depth in ``round_f64``."""
+ load_module("policy").eagle_harness_policy_decide_chain(
+ state, seq, slots, go_host, work_deltas, round_f64, depth, verify_num
+ )
+
+
+def eagle_harness_ranked_scores(
+ top_scores: torch.Tensor,
+ rows: torch.Tensor,
+ cols: torch.Tensor,
+ flat: torch.Tensor,
+ out: torch.Tensor,
+ out_count: torch.Tensor,
+) -> None:
+ """Cumulative ranked scores of ``top_scores[:rows[0], :cols[0]]`` (fp32,
+ unit column stride; sizes int32 ``[1]`` on the device) into ``out``
+ (fp32), bit for bit as
+ ``torch.cumsum(t.mean(dim=0), dim=0)``, or ``torch.cumsum(t.view(-1),
+ dim=0)`` when ``flat[0]`` (int32) is nonzero, computed on the contiguous
+ ``t``. ``out_count[0]`` (int32) gets their number: 0 for no rows or
+ columns, -1 for shapes past ``top_scores``, ``out``, 32 rows or 64
+ columns (whose torch reduction order is not replicated)."""
+ load_module("policy").eagle_harness_ranked_scores(
+ top_scores, rows, cols, flat, out, out_count
+ )
+
+
+def eagle_harness_policy_select_verify(
+ state: torch.Tensor,
+ recent: torch.Tensor,
+ hist: torch.Tensor,
+ published: torch.Tensor,
+ top_scores: torch.Tensor,
+ interval_i32: torch.Tensor,
+ interval_f64: torch.Tensor,
+ verify_i32: torch.Tensor,
+ verify_f64: torch.Tensor,
+ tree_depth: int,
+ exec_mode: int,
+) -> None:
+ """Publish ranked scores and choose the meaningful count for a fixed verify window.
+
+ Scores follow torch's default CUDA reduction order. History and shapes
+ are owned by DevicePolicy; exec_mode must be zero.
+ """
+ load_module("policy").eagle_harness_policy_select_verify(
+ state,
+ recent,
+ hist,
+ published,
+ top_scores,
+ interval_i32,
+ interval_f64,
+ verify_i32,
+ verify_f64,
+ tree_depth,
+ exec_mode,
+ )
diff --git a/eagle_harness/tokenspeed/tree_round/ops/rejection.py b/eagle_harness/tokenspeed/tree_round/ops/rejection.py
new file mode 100644
index 0000000..f8ab245
--- /dev/null
+++ b/eagle_harness/tokenspeed/tree_round/ops/rejection.py
@@ -0,0 +1,93 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Recursive tree rejection and residual-token sampling."""
+
+import functools
+from eagle_harness.tokenspeed.tree_round.ops.build import load_module
+
+import torch
+
+__all__ = ["residual_sample", "tree_reject_sample"]
+
+
+def _module():
+ return load_module("rejection")
+
+
+def tree_reject_sample(
+ probas: torch.Tensor,
+ tokens: torch.Tensor,
+ parents: torch.Tensor,
+ q_rows: torch.Tensor | None,
+ q_slot: torch.Tensor,
+ q_pos: torch.Tensor,
+ q_store: torch.Tensor,
+ qid_store: torch.Tensor,
+ coins: torch.Tensor,
+ top_ks: torch.Tensor,
+ argmax: torch.Tensor,
+ path: torch.Tensor,
+ predicts: torch.Tensor,
+ accept_length: torch.Tensor,
+ last_row: torch.Tensor,
+) -> None:
+ """Accept each request's draft tree against the target by rejection sampling.
+
+ ``probas`` (``[bs * N, V]`` fp32) holds the target's distribution at every
+ node row; the rows of tried nodes become their residuals. A node's children
+ (nodes whose ``parents`` entry it is, in index order) are tried in turn:
+ sampled ones (``q_slot`` >= 0 at the request's ``q_rows`` row of the
+ ``[R, N]`` tables, with q in ``q_store`` / ``qid_store`` ``[R, S, NC]``) by
+ recursive rejection without replacement, the others by their target mass
+ over the mass left; ``coins`` (``[bs, N]``) hold one uniform per child.
+ ``q_rows`` None: every child is deterministic. A sampled row whose residual
+ vanishes takes the target's argmax (``torch.argmax``'s) as its bonus.
+
+ Greedy rows (``top_ks``, ``[bs * N]`` int32, equal to 1) have a one-hot
+ target at ``argmax`` (``[bs * N]`` int64, read for them only): the first
+ child holding it is accepted, the others are rejected, and their
+ ``probas`` rows are never read (they may be unwritten).
+
+ Writes ``path`` (``[bs, N]`` int32, accepted nodes root first, -1 past the
+ path), ``predicts`` (``[bs * N]`` int32; the accepted children's tokens, the
+ bonus slot left for ``residual_sample``), ``accept_length``
+ (``[bs]``, accepted drafts plus the bonus) and ``last_row`` (``[bs]`` int64,
+ the last accepted node's row of ``probas``).
+ """
+ _module().tree_reject_sample(
+ probas,
+ tokens,
+ parents,
+ q_rows,
+ q_slot,
+ q_pos,
+ q_store,
+ qid_store,
+ coins,
+ top_ks,
+ argmax,
+ path,
+ predicts,
+ accept_length,
+ last_row,
+ )
+
+
+def residual_sample(
+ probas: torch.Tensor,
+ last_row: torch.Tensor,
+ coins: torch.Tensor,
+ top_ks: torch.Tensor,
+ argmax: torch.Tensor,
+ accept_length: torch.Tensor,
+ predicts: torch.Tensor,
+ num_nodes: int,
+) -> None:
+ """Draw each request's bonus token from row ``last_row[b]`` of ``probas``
+ (normalized or not) by inverse CDF with ``coins[b]``, into the end of its
+ accepted path in ``predicts`` (``[bs * num_nodes]``). A greedy last row
+ (``top_ks`` 1, per ``probas`` row) gives its ``argmax`` (int64, per
+ ``probas`` row) instead, its ``probas`` row unread."""
+ _module().residual_sample(probas, last_row, coins, top_ks, argmax, accept_length, predicts, num_nodes)
diff --git a/eagle_harness/tokenspeed/tree_round/ops/tree.py b/eagle_harness/tokenspeed/tree_round/ops/tree.py
new file mode 100644
index 0000000..6c6b999
--- /dev/null
+++ b/eagle_harness/tokenspeed/tree_round/ops/tree.py
@@ -0,0 +1,365 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""EAGLE-Harness draft-tree bookkeeping kernels (EAGLE-4); see
+``csrc/eagle_harness_tree.cu`` for the node pool layout."""
+
+import torch
+
+from eagle_harness.tokenspeed.tree_round.ops.build import load_module
+
+__all__ = [
+ "eagle_harness_draft_depth_update",
+ "eagle_harness_publish_draft_q",
+ "eagle_harness_residual_sample",
+ "eagle_harness_sample_children",
+ "eagle_harness_stable_topk_desc",
+ "eagle_harness_tree_reject_sample",
+ "eagle_harness_update_node_data",
+ "eagle_harness_work_deltas",
+ "eagle_harness_write_verify_tree",
+]
+
+
+def eagle_harness_update_node_data(
+ cumu_scores: torch.Tensor,
+ cumu_tokens: torch.Tensor,
+ work_scores: torch.Tensor,
+ sort_scores: torch.Tensor,
+ output_scores: torch.Tensor,
+ output_tokens: torch.Tensor,
+) -> None:
+ """Write the root's ``[bs, K]`` children into columns ``1..K`` of the pool,
+ work and sort lists."""
+ load_module("tree").eagle_harness_update_node_data(
+ cumu_scores, cumu_tokens, work_scores, sort_scores, output_scores, output_tokens
+ )
+
+
+def eagle_harness_work_deltas(
+ work_scores: torch.Tensor,
+ work_deltas: torch.Tensor,
+ live_rows: torch.Tensor,
+ node_count: torch.Tensor,
+ node_top_k: int,
+ verify_num: torch.Tensor,
+) -> None:
+ """``work_deltas[j]``: the mean over the first ``live_rows`` rows of the
+ best ``min(node_count + j, verify_num)`` scores of each row's two sorted
+ segments (``node_count`` best nodes, then the next depth's ``j`` best
+ frontier scores), ``j`` in ``0..node_top_k``. The counts are device int32
+ ``[1]`` (a captured launch serves every round); a zero ``node_count``
+ writes nothing. ``work_scores`` holds at most 32 rows; the
+ batch sum preserves the reference's 256-row reduction order."""
+ load_module("tree").eagle_harness_work_deltas(
+ work_scores, work_deltas, live_rows, node_count, node_top_k, verify_num
+ )
+
+
+def eagle_harness_draft_depth_update(
+ child_probs: torch.Tensor,
+ child_tokens: torch.Tensor,
+ expanded: torch.Tensor,
+ child_hidden: torch.Tensor,
+ frontier_tokens: torch.Tensor,
+ frontier_scores: torch.Tensor,
+ frontier_hidden: torch.Tensor,
+ frontier_index: torch.Tensor,
+ pool_tokens: torch.Tensor,
+ pool_scores: torch.Tensor,
+ pool_depths: torch.Tensor,
+ pool_prev: torch.Tensor,
+ pool_next: torch.Tensor,
+ pool_side: torch.Tensor,
+ work_scores: torch.Tensor,
+ sort_scores: torch.Tensor,
+ positions: torch.Tensor,
+ slot_starts: torch.Tensor,
+ lane_mask: torch.Tensor,
+ width: torch.Tensor,
+ depth: int,
+ cumu_count: torch.Tensor,
+ verify_num: torch.Tensor,
+ num_slots: int,
+) -> None:
+ """One draft depth's bookkeeping after its lane forward, in one launch
+ (one CTA per request row; per-request tensors are ``[rows, ...]``, read
+ through their strides). ``width``, ``cumu_count`` and ``verify_num`` are
+ device int32 ``[1]`` counts, so a captured launch serves every round.
+
+ The forward expanded the first ``width`` of each request's ``K`` lanes:
+ ``child_probs`` / ``child_tokens`` (``[rows, K, K]`` fp32 / int64, lanes
+ past ``width`` unread) are their children, ``expanded`` (``[rows, >= K]``
+ int64) their pool indices and ``child_hidden`` (``[rows, >= K, H]``, not
+ overlapping ``frontier_hidden``) their output hidden rows. A child's path score is
+ its probability times its lane's
+ ``frontier_scores`` entry. The children, sorted descending by the
+ bitonic network the frontier's tie order comes from, give the next
+ frontier, the best ``K`` (``[rows, K]``): ``frontier_tokens``,
+ ``frontier_scores``, ``frontier_index`` (pool indices) and
+ ``frontier_hidden`` (``[rows, K, H]``, their lanes' ``child_hidden``
+ rows). All children are appended to the pool (``pool_*``, ``[rows,
+ nodes]``) at node ``cumu_count`` on, at depth ``depth + 1``, scored
+ ``path score * 0.9999^(depth + 1)`` and linked (parent, first child,
+ next sibling). ``sort_scores`` keeps the best ``verify_num`` path scores
+ of its first ``min(verify_num, cumu_count)`` and the children (stable,
+ ties to the earlier); ``work_scores`` gets that head and the frontier's
+ scores for the next work deltas.
+
+ The lanes move one slot on: ``positions`` (``[rows, K]``) + 1,
+ ``slot_starts`` (``[rows]``) + K. When depth ``depth + 1`` fits in the
+ ``num_slots``-slot lane window, ``lane_mask`` (``[rows, K, words]``
+ int64, window slot ``j`` at bit ``j % 64`` of word ``j // 64``) becomes
+ the next depth's: lane ``r``'s parent lane's row plus slot
+ ``depth * K + r``.
+ """
+ load_module("tree").eagle_harness_draft_depth_update(
+ child_probs,
+ child_tokens,
+ expanded,
+ child_hidden,
+ frontier_tokens,
+ frontier_scores,
+ frontier_hidden,
+ frontier_index,
+ pool_tokens,
+ pool_scores,
+ pool_depths,
+ pool_prev,
+ pool_next,
+ pool_side,
+ work_scores,
+ sort_scores,
+ positions,
+ slot_starts,
+ lane_mask,
+ width,
+ depth,
+ cumu_count,
+ verify_num,
+ num_slots,
+ )
+
+
+def eagle_harness_stable_topk_desc(
+ scores: torch.Tensor,
+ live_rows: torch.Tensor,
+ n: torch.Tensor,
+ k: torch.Tensor,
+ out_values: torch.Tensor,
+ out_indices: torch.Tensor,
+) -> None:
+ """The first ``k`` entries of a stable descending sort (NaN first, ties to
+ the lower index) of the first ``n`` columns of each of the first
+ ``live_rows`` rows of ``[rows, <= 1024]`` float32 ``scores``, into the
+ first ``k`` columns of ``out_values`` / ``out_indices`` (``[rows, max_k]``
+ float32 / int64). ``live_rows``, ``n`` and ``k`` (``1 <= k <= n``) are
+ device int32 ``[1]``."""
+ load_module("tree").eagle_harness_stable_topk_desc(
+ scores, live_rows, n, k, out_values, out_indices
+ )
+
+
+def eagle_harness_write_verify_tree(
+ ranked: torch.Tensor,
+ cumu_tokens: torch.Tensor,
+ prev_indexs: torch.Tensor,
+ root_tokens: torch.Tensor,
+ rows: torch.Tensor,
+ input_map: torch.Tensor,
+ parent_map: torch.Tensor,
+ live_rows: torch.Tensor,
+ verify_num: torch.Tensor,
+) -> None:
+ """Write each of the first ``live_rows`` requests' verify tree into its
+ ``rows`` of the next round's ``input_map`` / ``parent_map`` (``[*, N]``
+ int32): slot ``i < verify_num`` is pool node ``ranked[b, i]``
+ (ancestor-first) with its parent's slot, the rest repeat
+ ``root_tokens[b]`` with parent -1. ``live_rows`` and ``verify_num`` are
+ device int32 ``[1]``."""
+ load_module("tree").eagle_harness_write_verify_tree(
+ ranked,
+ cumu_tokens,
+ prev_indexs,
+ root_tokens,
+ rows,
+ input_map,
+ parent_map,
+ live_rows,
+ verify_num,
+ )
+
+
+def eagle_harness_sample_children(
+ logits: torch.Tensor,
+ candidates: torch.Tensor,
+ tokens: torch.Tensor,
+ scores: torch.Tensor,
+ temperatures: torch.Tensor,
+ top_ks: torch.Tensor,
+ top_ps: torch.Tensor,
+ q_store: torch.Tensor,
+ qid_store: torch.Tensor,
+ node_slot: torch.Tensor,
+ node_pos: torch.Tensor,
+ width: torch.Tensor | None,
+ slot_base: int,
+ cumu_start: torch.Tensor,
+ vocab_limit: int,
+ seed: int,
+ round_counter: torch.Tensor,
+ launch: int,
+) -> None:
+ """Draw each expanded row's children from its draft distribution.
+
+ The rows are ``R`` per request, as ``[B, R, *]`` views read through their
+ strides, of which each request expands its first ``width`` (a device
+ int32 ``[1]``; None: all ``R``). ``cumu_start`` is a device int32 ``[1]``. For rows of requests with ``temperatures > 0``,
+ overwrite ``tokens`` (``[B, R, K]`` int64) with ``K`` candidates drawn
+ without replacement from the softmax of ``logits / temperature`` over
+ the row's candidates (``[B, R, NC]`` fp32 logits, int64 ids), cut to the
+ request's top-k / top-p; ``scores`` (``[B, R, K]``, q's sorted top-K)
+ are kept, a child past the cut's support set to 0. Row ``r``'s q and ids
+ go to slot ``slot_base + r`` of ``q_store`` / ``qid_store``
+ (``[B, S, NC]``) and each child's slot and candidate position to
+ ``node_slot`` / ``node_pos`` (``[B, nodes]`` int32) at pool nodes
+ ``cumu_start + r * K`` on; greedy rows keep their children with slot -1.
+ The draws come from Philox stream ``round_counter[0] * 64 + launch``
+ keyed by expanded row ``b * width + r`` and candidate, so a captured
+ graph draws afresh as the device counter moves.
+ """
+ load_module("tree").eagle_harness_sample_children(
+ logits,
+ candidates,
+ tokens,
+ scores,
+ temperatures,
+ top_ks,
+ top_ps,
+ q_store,
+ qid_store,
+ node_slot,
+ node_pos,
+ width,
+ slot_base,
+ cumu_start,
+ vocab_limit,
+ seed,
+ round_counter,
+ launch,
+ )
+
+
+def eagle_harness_tree_reject_sample(
+ probas: torch.Tensor,
+ tokens: torch.Tensor,
+ parents: torch.Tensor,
+ q_rows: torch.Tensor | None,
+ q_slot: torch.Tensor,
+ q_pos: torch.Tensor,
+ q_store: torch.Tensor,
+ qid_store: torch.Tensor,
+ coins: torch.Tensor,
+ top_ks: torch.Tensor,
+ argmax: torch.Tensor,
+ path: torch.Tensor,
+ predicts: torch.Tensor,
+ accept_length: torch.Tensor,
+ last_row: torch.Tensor,
+) -> None:
+ """Accept each request's draft tree against the target by rejection sampling.
+
+ ``probas`` (``[bs * N, V]`` fp32) holds the target's distribution at every
+ node row; the rows of tried nodes become their residuals. A node's children
+ (nodes whose ``parents`` entry it is, in index order) are tried in turn:
+ sampled ones (``q_slot`` >= 0 at the request's ``q_rows`` row of the
+ ``[R, N]`` tables, with q in ``q_store`` / ``qid_store`` ``[R, S, NC]``) by
+ recursive rejection without replacement, the others by their target mass
+ over the mass left; ``coins`` (``[bs, N]``) hold one uniform per child.
+ ``q_rows`` None: every child is deterministic. A sampled row whose residual
+ vanishes takes the target's argmax (``torch.argmax``'s) as its bonus.
+
+ Greedy rows (``top_ks``, ``[bs * N]`` int32, equal to 1) have a one-hot
+ target at ``argmax`` (``[bs * N]`` int64, read for them only): the first
+ child holding it is accepted, the others are rejected, and their
+ ``probas`` rows are never read (they may be unwritten).
+
+ Writes ``path`` (``[bs, N]`` int32, accepted nodes root first, -1 past the
+ path), ``predicts`` (``[bs * N]`` int32; the accepted children's tokens, the
+ bonus slot left for ``eagle_harness_residual_sample``), ``accept_length``
+ (``[bs]``, accepted drafts plus the bonus) and ``last_row`` (``[bs]`` int64,
+ the last accepted node's row of ``probas``).
+ """
+ load_module("tree").eagle_harness_tree_reject_sample(
+ probas,
+ tokens,
+ parents,
+ q_rows,
+ q_slot,
+ q_pos,
+ q_store,
+ qid_store,
+ coins,
+ top_ks,
+ argmax,
+ path,
+ predicts,
+ accept_length,
+ last_row,
+ )
+
+
+def eagle_harness_residual_sample(
+ probas: torch.Tensor,
+ last_row: torch.Tensor,
+ coins: torch.Tensor,
+ top_ks: torch.Tensor,
+ argmax: torch.Tensor,
+ accept_length: torch.Tensor,
+ predicts: torch.Tensor,
+ num_nodes: int,
+) -> None:
+ """Draw each request's bonus token from row ``last_row[b]`` of ``probas``
+ (normalized or not) by inverse CDF with ``coins[b]``, into the end of its
+ accepted path in ``predicts`` (``[bs * num_nodes]``). A greedy last row
+ (``top_ks`` 1, per ``probas`` row) gives its ``argmax`` (int64, per
+ ``probas`` row) instead, its ``probas`` row unread."""
+ load_module("tree").eagle_harness_residual_sample(
+ probas, last_row, coins, top_ks, argmax, accept_length, predicts, num_nodes
+ )
+
+
+def eagle_harness_publish_draft_q(
+ ranked: torch.Tensor,
+ node_slot: torch.Tensor,
+ node_pos: torch.Tensor,
+ q_round: torch.Tensor,
+ qid_round: torch.Tensor,
+ rows: torch.Tensor,
+ q_tab: torch.Tensor,
+ qid_tab: torch.Tensor,
+ slot_tab: torch.Tensor,
+ pos_tab: torch.Tensor,
+ live_rows: torch.Tensor,
+ verify_num: torch.Tensor,
+) -> None:
+ """Copy each of the first ``live_rows`` requests' round q (``[rows, S,
+ NC]``) into row ``rows[b]`` of the ``[R, S, NC]`` tables, and write per
+ verify node ``i < verify_num`` (pool node ``ranked[b, i]``) its parent's
+ slot and candidate position into the ``[R, N]`` tables; -1 for the root
+ and slots past ``verify_num``. ``live_rows`` and ``verify_num`` are device
+ int32 ``[1]``."""
+ load_module("tree").eagle_harness_publish_draft_q(
+ ranked,
+ node_slot,
+ node_pos,
+ q_round,
+ qid_round,
+ rows,
+ q_tab,
+ qid_tab,
+ slot_tab,
+ pos_tab,
+ live_rows,
+ verify_num,
+ )
diff --git a/eagle_harness/tokenspeed/tree_round/policy_cost.py b/eagle_harness/tokenspeed/tree_round/policy_cost.py
new file mode 100644
index 0000000..0e02f58
--- /dev/null
+++ b/eagle_harness/tokenspeed/tree_round/policy_cost.py
@@ -0,0 +1,430 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Pack caller-computed tree and chain costs into the device policy ABI.
+
+Records are structural: callers need no engine base class. Policy formulas,
+measurement selection and tier decisions belong to the producer, not here.
+"""
+
+from __future__ import annotations
+
+import itertools
+import math
+from dataclasses import dataclass
+from typing import Protocol
+
+import torch
+
+
+class TreeIntervalCosts(Protocol):
+ """One measured context interval, including this live batch's verify decision."""
+
+ @property
+ def verify_widths(self) -> tuple[int, ...]: ...
+
+ @property
+ def verify_cost_deltas(self) -> tuple[tuple[float, ...], ...]: ...
+
+ @property
+ def draft_cost(self) -> float: ...
+
+ @property
+ def model_cost_ratio(self) -> float: ...
+
+ @property
+ def depth_thresholds(self) -> tuple[tuple[float, ...], ...]: ...
+
+ @property
+ def verify_tier(self) -> int: ...
+
+ @property
+ def verify_thresholds(self) -> tuple[float, float]: ...
+
+
+class TreeBatchCosts(Protocol):
+ """Costs for one live batch; cost_batch_size identifies its measured row."""
+
+ @property
+ def cost_batch_size(self) -> int: ...
+
+ @property
+ def cache_length_step(self) -> int: ...
+
+ @property
+ def intervals(self) -> tuple[TreeIntervalCosts, ...]: ...
+
+
+class TreePolicyCosts(Protocol):
+ """Immutable host records for live batches 1..32 and five tier variants."""
+
+ @property
+ def batches(self) -> tuple[TreeBatchCosts, ...]: ...
+
+ @property
+ def history_floors(self) -> tuple[int, ...]: ...
+
+ @property
+ def initial_widths(self) -> tuple[int, ...]: ...
+
+ @property
+ def async_layer_ratio(self) -> float: ...
+
+
+class ChainStopTerms(Protocol):
+ """Core terms: gain_scale and cliff_gain_scale are denominators, not reciprocals."""
+
+ @property
+ def gain_scale(self) -> float: ...
+
+ @property
+ def cost(self) -> float: ...
+
+ @property
+ def threshold(self) -> float: ...
+
+ @property
+ def cliff_gain_scale(self) -> float: ...
+
+ @property
+ def cliff_cost(self) -> float: ...
+
+
+class ChainPolicyBatch(Protocol):
+ @property
+ def cache_length_step(self) -> int: ...
+
+ @property
+ def intervals(self) -> tuple[tuple[ChainStopTerms, ...], ...]: ...
+
+
+class ChainPolicyCosts(Protocol):
+ """Core-computed terms indexed by live batch 1..512, interval and depth."""
+
+ @property
+ def batches(self) -> tuple[ChainPolicyBatch, ...]: ...
+
+
+@dataclass(frozen=True)
+class PolicyTables:
+ batch_table: torch.Tensor # int64 [max_bs, 5]; chain cost ID is live batch - 1
+ interval_i32: torch.Tensor # int32 [costs, intervals, 1 + measured widths]
+ interval_f64: torch.Tensor # float64 [costs, intervals, 2 + 5*depth + widths**2]
+ tier_table: torch.Tensor # int32 [9]: five history floors, four draft widths
+ verify_i32: torch.Tensor # int32 [32, intervals]: tier
+ verify_f64: torch.Tensor # float64 [32, intervals, 2]: stability thresholds
+ chain_f64: torch.Tensor # float64 [512, intervals, 2, depth, 5]; empty for trees
+
+
+def _shared_row(batch: TreeBatchCosts) -> tuple:
+ # Verify decisions depend on the live batch even when its measurement is shared.
+ return (
+ batch.cache_length_step,
+ tuple(
+ (
+ interval.verify_widths,
+ interval.verify_cost_deltas,
+ interval.draft_cost,
+ interval.model_cost_ratio,
+ interval.depth_thresholds,
+ )
+ for interval in batch.intervals
+ ),
+ )
+
+
+def _check_costs(costs: TreePolicyCosts) -> int:
+ if len(costs.batches) != 32:
+ raise ValueError("tree policy costs need 32 live batch records")
+ if len(costs.history_floors) != 5 or len(costs.initial_widths) != 4:
+ raise ValueError(
+ "tree policy costs need five history floors and four initial widths"
+ )
+ if any(type(v) is not int or not 1 <= v < 2**31 for v in costs.history_floors):
+ raise ValueError("history floors must be positive int32 values")
+ if any(type(v) is not int or not 1 <= v <= 8 for v in costs.initial_widths):
+ raise ValueError("initial widths must be integers in 1..8")
+ if not math.isfinite(costs.async_layer_ratio) or costs.async_layer_ratio <= 0:
+ raise ValueError("async_layer_ratio must be positive and finite")
+ depth = None
+ for batch in costs.batches:
+ if type(batch.cost_batch_size) is not int or batch.cost_batch_size < 1:
+ raise ValueError("measured batch sizes must be positive integers")
+ if (
+ type(batch.cache_length_step) is not int
+ or not 0 < batch.cache_length_step < 2**63
+ ):
+ raise ValueError("cache_length_step must be a positive int64")
+ if not batch.intervals:
+ raise ValueError("each batch needs at least one interval")
+ for interval in batch.intervals:
+ widths = interval.verify_widths
+ if (
+ not 1 <= len(widths) <= 32
+ or any(type(w) is not int or not 0 <= w < 2**31 - 1 for w in widths)
+ or widths[0] != 0
+ or any(a >= b for a, b in itertools.pairwise(widths))
+ ):
+ raise ValueError(
+ "interval needs 1..32 increasing widths starting at index 0"
+ )
+ if (
+ not math.isfinite(interval.draft_cost)
+ or interval.draft_cost <= 0
+ or not math.isfinite(interval.model_cost_ratio)
+ or not 5 <= interval.model_cost_ratio <= 100
+ ):
+ raise ValueError(
+ "interval needs positive finite draft cost and model ratio in [5, 100]"
+ )
+ thresholds = interval.depth_thresholds
+ if len(thresholds) != 5 or not 2 <= len(thresholds[0]) <= 32:
+ raise ValueError("depth thresholds need five variants of 2..32 depths")
+ if depth is None:
+ depth = len(thresholds[0])
+ if any(
+ len(row) != depth or any(not math.isfinite(v) for v in row)
+ for row in thresholds
+ ):
+ raise ValueError(
+ "depth thresholds must be finite with the same depth in every interval"
+ )
+ deltas = interval.verify_cost_deltas
+ if len(deltas) != len(widths) or any(
+ len(row) != len(widths)
+ or any(not math.isfinite(v) or v < 0 for v in row)
+ for row in deltas
+ ):
+ raise ValueError(
+ "verify cost deltas must be a finite nonnegative square matrix over widths"
+ )
+ if not 0 <= interval.verify_tier <= 3:
+ raise ValueError("verify tier must be in 0..3")
+ if len(interval.verify_thresholds) != 2 or any(
+ not math.isfinite(v) or v <= 0 for v in interval.verify_thresholds
+ ):
+ raise ValueError("verify thresholds must be two positive finite values")
+ assert depth is not None
+ return depth
+
+
+def build_tables(costs: TreePolicyCosts, *, device: torch.device) -> PolicyTables:
+ """Pack structural cost records on CPU and upload each completed tensor once.
+
+ Args:
+ costs: Records for live batches 1..32. Repeated measured batch IDs must
+ carry identical shared interval data; verify decisions may differ.
+ device: Destination device; CPU supports exact packing checks.
+
+ Returns:
+ Contiguous tables preserving the tree ABI and float64 values exactly.
+ Padding and reserved chain columns remain zero; chain_f64 is empty.
+ """
+ depth = _check_costs(costs)
+ unique: dict[int, TreeBatchCosts] = {}
+ for batch in costs.batches:
+ previous = unique.setdefault(batch.cost_batch_size, batch)
+ if _shared_row(previous) != _shared_row(batch):
+ raise ValueError(
+ f"conflicting costs for measured batch {batch.cost_batch_size}"
+ )
+ ids = {measured: i for i, measured in enumerate(unique)}
+ intervals = max(len(batch.intervals) for batch in unique.values())
+ max_widths = max(
+ len(row.verify_widths) for batch in unique.values() for row in batch.intervals
+ )
+ batch_table = torch.zeros((32, 5), dtype=torch.int64)
+ interval_i32 = torch.zeros(
+ (len(unique), intervals, 1 + max_widths), dtype=torch.int32
+ )
+ interval_f64 = torch.zeros(
+ (len(unique), intervals, 2 + 5 * depth + max_widths**2), dtype=torch.float64
+ )
+ verify_i32 = torch.zeros((32, intervals), dtype=torch.int32)
+ verify_f64 = torch.zeros((32, intervals, 2), dtype=torch.float64)
+ for measured, batch in unique.items():
+ for i, interval in enumerate(batch.intervals):
+ n = len(interval.verify_widths)
+ interval_i32[ids[measured], i, : 1 + n] = torch.tensor(
+ [n, *interval.verify_widths], dtype=torch.int32
+ )
+ packed = interval_f64[ids[measured], i]
+ packed[: 2 + 5 * depth] = torch.tensor(
+ [
+ interval.draft_cost,
+ interval.model_cost_ratio,
+ *itertools.chain.from_iterable(interval.depth_thresholds),
+ ],
+ dtype=torch.float64,
+ )
+ packed[2 + 5 * depth :].view(max_widths, max_widths)[:n, :n] = torch.tensor(
+ interval.verify_cost_deltas, dtype=torch.float64
+ )
+ for i, batch in enumerate(costs.batches):
+ batch_table[i] = torch.tensor(
+ [
+ ids[batch.cost_batch_size],
+ 0,
+ len(batch.intervals),
+ batch.cache_length_step,
+ 0,
+ ],
+ dtype=torch.int64,
+ )
+ for j, interval in enumerate(batch.intervals):
+ verify_i32[i, j] = interval.verify_tier
+ verify_f64[i, j] = torch.tensor(
+ interval.verify_thresholds, dtype=torch.float64
+ )
+ return PolicyTables(
+ batch_table=batch_table.to(device),
+ interval_i32=interval_i32.to(device),
+ interval_f64=interval_f64.to(device),
+ tier_table=torch.tensor(
+ (*costs.history_floors, *costs.initial_widths),
+ dtype=torch.int32,
+ device=device,
+ ),
+ verify_i32=verify_i32.to(device),
+ verify_f64=verify_f64.to(device),
+ chain_f64=torch.zeros(0, dtype=torch.float64, device=device),
+ )
+
+
+def build_chain_tables(
+ costs: ChainPolicyCosts | None,
+ *,
+ tree_depth: int,
+ verify_num: int,
+ chain_width_table: tuple[tuple[int, int], ...],
+ device: torch.device,
+) -> PolicyTables:
+ """Pack chain terms unchanged; no cost model or tier classification runs here.
+
+ Args:
+ costs: Structural records for every live batch 1..512. Each interval
+ has one term record per depth, zero at depths without a decision.
+ ``gain_scale`` is the denominator in ``raw_gain * 2 / gain_scale``;
+ the cliff pair is either both positive or both zero.
+ tree_depth: Chain depth in 2..15, matching every interval.
+ verify_num: Fixed verify capacity in 2..16.
+ chain_width_table: Increasing positive ``(min_batch_size, width)`` pairs.
+ The greatest covered threshold supplies the round's fixed width;
+ uncovered batches use the confidence rule.
+ device: Destination device; CPU supports packing and validation tests.
+
+ Returns:
+ Contiguous tables with cost ID ``live_batch - 1`` and tier row zero.
+ Both ABI tier rows contain identical terms. Interval padding is zero;
+ tree-only tensors are empty.
+ """
+ if (
+ type(tree_depth) is not int
+ or not 2 <= tree_depth <= 15
+ or type(verify_num) is not int
+ or not 2 <= verify_num <= 16
+ ):
+ raise ValueError("chain policy needs depth in 2..15 and verify_num in 2..16")
+ previous = 0
+ for entry in chain_width_table:
+ if (
+ not isinstance(entry, tuple)
+ or len(entry) != 2
+ or any(type(v) is not int for v in entry)
+ or not previous < entry[0]
+ or not 2 <= entry[1] <= min(tree_depth + 1, verify_num)
+ ):
+ raise ValueError(
+ "chain width table needs increasing positive integer thresholds "
+ "and widths in 2..min(depth + 1, verify_num)"
+ )
+ previous = entry[0]
+ if costs is None:
+ if not chain_width_table or chain_width_table[0][0] != 1:
+ raise ValueError(
+ "an uncalibrated chain width table must cover every batch starting at 1"
+ )
+ batch_table = torch.zeros((512, 5), dtype=torch.int64)
+ width = chain_width_table[0][1]
+ for i in range(512):
+ for minimum, candidate in chain_width_table:
+ if i + 1 < minimum:
+ break
+ width = candidate
+ batch_table[i] = torch.tensor([0, 0, 1, 1, width])
+ # Table rounds return before reading any cost. These are unused ABI buffers,
+ # not fabricated timings; uncovered batches above are rejected.
+ return PolicyTables(
+ batch_table=batch_table.to(device),
+ interval_i32=torch.zeros(0, dtype=torch.int32, device=device),
+ interval_f64=torch.zeros(0, dtype=torch.float64, device=device),
+ tier_table=torch.zeros(0, dtype=torch.int32, device=device),
+ verify_i32=torch.zeros(0, dtype=torch.int32, device=device),
+ verify_f64=torch.zeros(0, dtype=torch.float64, device=device),
+ chain_f64=torch.zeros(
+ (512, 1, 2, tree_depth, 5), dtype=torch.float64, device=device
+ ),
+ )
+ if len(costs.batches) != 512:
+ raise ValueError("chain policy costs need 512 live batch records")
+ rows = []
+ for batch in costs.batches:
+ if (
+ type(batch.cache_length_step) is not int
+ or not 0 < batch.cache_length_step < 2**63
+ or not batch.intervals
+ ):
+ raise ValueError(
+ "chain batch needs intervals and a positive int64 cache step"
+ )
+ intervals = []
+ for interval in batch.intervals:
+ if len(interval) != tree_depth:
+ raise ValueError("chain cost records must match the policy tree_depth")
+ packed = []
+ for depth, terms in enumerate(interval):
+ values = (
+ terms.gain_scale,
+ terms.cost,
+ terms.threshold,
+ terms.cliff_gain_scale,
+ terms.cliff_cost,
+ )
+ if any(not math.isfinite(v) for v in values):
+ raise ValueError("chain stop terms must be finite")
+ if depth >= 2 and depth % 2 == 0 and depth < tree_depth - 1:
+ if any(v <= 0 for v in values[:3]) or not (
+ values[3] == values[4] == 0 or values[3] > 0 and values[4] > 0
+ ):
+ raise ValueError(
+ "chain decision needs positive denominator, cost and threshold; "
+ "cliff terms must both be positive or both zero"
+ )
+ elif any(v != 0 for v in values):
+ raise ValueError("unused chain depth slots must be zero")
+ packed.append(values)
+ intervals.append(packed)
+ rows.append(intervals)
+ max_intervals = max(len(row) for row in rows)
+ chain_f64 = torch.zeros((512, max_intervals, 2, tree_depth, 5), dtype=torch.float64)
+ batch_table = torch.zeros((512, 5), dtype=torch.int64)
+ for i, (batch, intervals) in enumerate(zip(costs.batches, rows)):
+ n = len(intervals)
+ chain_f64[i, :n] = torch.tensor(intervals, dtype=torch.float64).unsqueeze(1)
+ width = 0
+ for min_batch_size, candidate in chain_width_table:
+ if i + 1 < min_batch_size:
+ break
+ width = candidate
+ batch_table[i] = torch.tensor(
+ [i, 0, n, batch.cache_length_step, width], dtype=torch.int64
+ )
+ return PolicyTables(
+ batch_table=batch_table.to(device),
+ interval_i32=torch.zeros(0, dtype=torch.int32, device=device),
+ interval_f64=torch.zeros(0, dtype=torch.float64, device=device),
+ tier_table=torch.zeros(0, dtype=torch.int32, device=device),
+ verify_i32=torch.zeros(0, dtype=torch.int32, device=device),
+ verify_f64=torch.zeros(0, dtype=torch.float64, device=device),
+ chain_f64=chain_f64.to(device),
+ )
diff --git a/eagle_harness/vllm/calibrate.py b/eagle_harness/vllm/calibrate.py
index a802253..82b8637 100644
--- a/eagle_harness/vllm/calibrate.py
+++ b/eagle_harness/vllm/calibrate.py
@@ -16,7 +16,14 @@ from typing import Any
import torch
-from eagle_harness.core.calibration import AttentionShape, CalibrationPaths, MeasureParams, StepTiming, fit_step_timings
+from eagle_harness.core.calibration import (
+ AttentionShape,
+ CalibrationPaths,
+ MeasureParams,
+ StepTiming,
+ attention_shape,
+ fit_step_timings,
+)
from eagle_harness.core.limits import MAX_CHAIN_VERIFY_NUM, ComputeIntensity
from eagle_harness.core.live_costs import CostKey, config_digest, write_key
@@ -375,28 +382,6 @@ def cost_key(model: str, draft: str, tp: int, dtype: Any) -> CostKey:
)
-def attention_shape(config: Any) -> AttentionShape:
- """Read attention counts from a text config, refusing unknown layer layouts."""
- config = getattr(config, "text_config", config)
- layers = getattr(config, "num_hidden_layers", 0)
- types = getattr(config, "layer_types", None)
- window = getattr(config, "sliding_window", None) or 0
- if types is None:
- if getattr(config, "full_attention_interval", None) or getattr(config, "hybrid_override_pattern", None):
- raise ValueError("hybrid calibration needs explicit layer_types in the model config")
- types = [
- "sliding_attention" if window and getattr(config, "use_sliding_window", True) else "full_attention"
- ] * layers
- known = {"full_attention", "sliding_attention", "linear_attention", "mamba"}
- if len(types) != layers or set(types) - known:
- raise ValueError(f"cannot infer attention layout for calibration: {types!r}")
- count = sum(kind in {"full_attention", "sliding_attention"} for kind in types)
- sliding = types.count("sliding_attention")
- if count < 1 or (sliding and window <= 0):
- raise ValueError("calibration needs attention layers and a positive window for sliding attention")
- return AttentionShape(count, sliding, window)
-
-
def validate_tables(data_path: str, *, context_stop: int | None = None) -> None:
"""Require complete, readable batch-one tables before publishing a serve command."""
from eagle_harness.core.cost_table import load_cost_tables
diff --git a/pyproject.toml b/pyproject.toml
index e3552ef..f2f5b26 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -48,6 +48,7 @@ include = ["eagle_harness*"]
[tool.setuptools.package-data]
"eagle_harness.core" = ["*.csv", "profiles/**/*.json", "profiles/**/*.csv", "profiles/**/*.md"]
"eagle_harness.kernels" = ["csrc/*.cu", "_native/*/*.so"]
+"eagle_harness.tokenspeed.tree_round.ops" = ["csrc/*.cu", "csrc/*.h"]
[tool.pytest.ini_options]
testpaths = ["tests"]
diff --git a/tests/test_eagle4_model.py b/tests/test_eagle4_model.py
index f9c1279..b5c14d4 100644
--- a/tests/test_eagle4_model.py
+++ b/tests/test_eagle4_model.py
@@ -234,6 +234,63 @@ def test_the_layer_attends_over_the_fused_input_and_reduces_a_moe_partial_sum(mo
assert torch.equal(mlp, (attn - res) * 3 * scale)
+def _prefill_batch(mode, capture="LAST", return_logprob=False, lens=(2, 3)):
+ from sglang.srt.model_executor.forward_batch_info import CaptureHiddenMode, ForwardMode
+
+ hidden = torch.arange(sum(lens) * 2, dtype=torch.float32).view(-1, 2)
+ return SimpleNamespace(
+ forward_mode=getattr(ForwardMode, mode),
+ return_logprob=return_logprob,
+ capture_hidden_mode=getattr(CaptureHiddenMode, capture),
+ extend_seq_lens=torch.tensor(lens),
+ spec_info=SimpleNamespace(hidden_states=hidden),
+ )
+
+
+def _model(norm_output: bool, mlp_rows: list):
+ """An ``Eagle4Model`` shell over the affine layer shell; ``mlp_rows`` records how many rows each MLP call got."""
+ model = object.__new__(llama_eagle4.Eagle4Model)
+ torch.nn.Module.__init__(model)
+ model.hidden_size, model.norm_output = 2, norm_output
+ layer = _layer(attn_norm=False, reduce_mlp=False)
+ layer.self_attn = lambda positions, hidden_states, forward_batch: hidden_states[:, :2] + hidden_states[:, 2:] + 100
+
+ def mlp(x):
+ mlp_rows.append(x.shape[0])
+ return x * 3
+
+ layer.mlp = mlp
+ model.layers = [layer]
+ model.norm = lambda x: x * 0.5
+ model._embed = lambda ids: ids[:, None].float().expand(-1, 2) / 7
+ return model
+
+
[email protected]("norm_output", [True, False])
+def test_a_prefill_runs_the_mlp_on_each_request_last_row_only(norm_output):
+ ids = torch.arange(5)
+ rows: list = []
+ model = _model(norm_output, rows)
+ full_normed, (full_aux,) = model(ids, None, _prefill_batch("EXTEND", capture="FULL"))
+ assert rows == [5]
+ for mode in ("EXTEND", "MIXED"):
+ rows.clear()
+ normed, (aux,) = model(ids, None, _prefill_batch(mode))
+ assert rows == [2] # one row per request, the attention saw all 5
+ last = torch.tensor([1, 4])
+ assert torch.equal(normed[last], full_normed[last]) and torch.equal(aux[last], full_aux[last])
+ assert normed.shape == full_normed.shape and aux.shape == full_aux.shape
+
+
+ "mode, capture, return_logprob",
+ [("DECODE", "LAST", False), ("TARGET_VERIFY", "LAST", False), ("DRAFT_EXTEND_V2", "LAST", False),
+ ("EXTEND", "FULL", False), ("EXTEND", "LAST", True)],
+)
+def test_other_forwards_run_the_mlp_on_every_row(mode, capture, return_logprob):
+ assert llama_eagle4.prefill_read_rows(_prefill_batch(mode, capture, return_logprob)) is None
+
+
# --- The real Nemotron draft config, the latent MoE block and its checkpoint experts ---
diff --git a/tests/test_engine_release.py b/tests/test_engine_release.py
index a82e211..9282826 100644
--- a/tests/test_engine_release.py
+++ b/tests/test_engine_release.py
@@ -88,9 +88,10 @@ def wheels(tmp_path, channel):
else {
"sglang": "0.5.23.dev252+eagle.4",
"vllm": "0.32.0rc1.dev283+eagle.4",
- "tokenspeed": "0.1.1+eagle.4",
- "tokenspeed-kernel": "0.1.1+eagle.4",
- "tokenspeed-scheduler": "0.1.1+eagle.4",
+ "tokenspeed": "0.1.1+eagle.8",
+ "tokenspeed-kernel": "0.1.4+eagle.8",
+ "tokenspeed-scheduler": "0.1.42+eagle.8",
+ "tokenspeed-engine": "0.1.0+eagle.8",
}
)
result = []
@@ -257,13 +258,17 @@ def test_manifest_changes_are_refused_without_uploading(tmp_path, release):
assert not any(args[1] == "upload" for args in calls(log))
[email protected]("case", ["missing-companions", "wrong-channel", "harness", "duplicate", "upstream"])
+ "missing-companions", "missing-control-plane", "wrong-channel", "harness", "duplicate", "upstream",
+])
def test_invalid_upload_is_rejected_before_contacting_github(tmp_path, release, case):
_, log = release
artifacts = wheels(tmp_path, "cu130")
channel = "cu130"
if case == "missing-companions":
artifacts = artifacts[:1]
+ elif case == "missing-control-plane":
+ artifacts = [wheel for wheel in artifacts if not wheel.name.startswith("tokenspeed_engine-")]
elif case == "wrong-channel":
channel = "rocm"
elif case == "duplicate":
diff --git a/tests/test_install_docs.py b/tests/test_install_docs.py
index 5a7c55b..25cf688 100644
--- a/tests/test_install_docs.py
+++ b/tests/test_install_docs.py
@@ -66,6 +66,8 @@ def test_copy_paste_commands_use_the_release_pins(guide):
}
indexes = {s[k] for k in ("EAGLE_CUDA_INDEX", "EAGLE_TORCH_CUDA_INDEX", "EAGLE_NVIDIA_INDEX")}
images = {s[k] for k in ("EAGLE_SGLANG_IMAGE", "EAGLE_VLLM_IMAGE", "EAGLE_TOKENSPEED_IMAGE")}
+ for image in re.findall(r"ghcr\.io/eagle-hq/[\w.-]+:\d+\.\d+\.\d+", guide.read_text()):
+ assert image in images, f"{guide.name}: {image} does not match release.env"
for block in bash_blocks(guide):
for package, version in re.findall(r'"(sglang|vllm|tokenspeed(?:-\w+)?)==([^"\s]+)"', block):
assert version == pins[package], f"{guide.name}: {package}=={version}, release.env pins {pins[package]}"
@@ -98,6 +100,20 @@ def test_copy_paste_commands_never_pin_the_harness():
assert not re.search(r"eagle-harness(\[\w+\])?==\d", block), f"{guide.name}: {block}"
+def test_tokenspeed_install_names_only_the_new_release_source_and_builds():
+ install = (REPO / "docs/install.md").read_text()
+ links = re.findall(r"https://github\.com/eagle-hq/tokenspeed[^)\s]*", install)
+ assert links == ["https://github.com/eagle-hq/tokenspeed/tree/eagle/v0.1.3"]
+ pins = re.findall(r'"(tokenspeed(?:-\w+)?)==([^"\s]+)"', section(REPO / "docs/install.md", "## TokenSpeed CUDA"))
+ assert dict(pins) == {"tokenspeed": "0.1.1+eagle.8", "tokenspeed-kernel": "0.1.4+eagle.8",
+ "tokenspeed-scheduler": "0.1.42+eagle.8", "tokenspeed-engine": "0.1.0+eagle.8"}
+
+
+def test_docs_do_not_reintroduce_withdrawn_tokenspeed_pins():
+ for path in [REPO / "CHANGELOG.md", *GUIDES, *sorted((REPO / "docs/release-notes").glob("*.md"))]:
+ assert not re.search(r"tokenspeed[^\n]*\+eagle\.(?:5|7)\b", path.read_text(), re.I), path
+
+
def test_rocm_install_uses_public_indexes_and_the_shipped_lock():
install = section(REPO / "docs/install.md", "## SGLang ROCm on AMD")
block = re.findall(r"```bash\n(.*?)```", install, re.S)[0]
diff --git a/tests/test_plain_decode.py b/tests/test_plain_decode.py
index 000ee93..ed6a91e 100644
--- a/tests/test_plain_decode.py
+++ b/tests/test_plain_decode.py
@@ -98,7 +98,7 @@ def test_worker_off_dispatch_skips_draft_verify_and_prelaunch(monkeypatch):
)
batch = SimpleNamespace(forward_mode=ForwardMode.DECODE, is_extend_in_batch=False, reqs=[Request()])
result = SimpleNamespace(new_seq_lens=[5], new_seq_lens_cpu=[5])
- monkeypatch.setattr(plain_module, "plain_decode", lambda *args: calls.append("decode") or result)
+ monkeypatch.setattr(plain_module, "plain_decode", lambda *args, **kwargs: calls.append("decode") or result)
worker._native_decode._requests.publishes_host_lengths = True
on_publish = lambda lengths, **host: calls.append(("publish", lengths, host)) # noqa: E731
assert worker.forward_batch_generation(batch, on_publish=on_publish) is result
@@ -286,3 +286,320 @@ def test_plain_decode_restores_spec_state_when_target_raises():
plain_decode(batch, SimpleNamespace(forward_batch_generation=forward), torch.arange(4).reshape(1, 4))
assert batch.spec_info is draft and batch.spec_algorithm is algorithm
assert draft.bonus_tokens.tolist() == [17]
+
+
[email protected]("tracking", [False, True])
+def test_plain_decode_saves_mamba_states_on_the_track_grid_like_a_no_spec_decode(monkeypatch, tracking):
+ pytest.importorskip("sglang")
+ import torch
+ from sglang.srt import runtime_context
+ from sglang.srt.speculative import spec_utils
+
+ from eagle_harness.sglang.plain_decode import plain_decode
+
+ monkeypatch.setattr(runtime_context, "mamba_track_grid", lambda page_size: 8, raising=False)
+ planned = []
+
+ def prepare(batch): # the engine's verify-time track plan: slots only, no mask
+ planned.append(batch.seq_lens.tolist())
+ batch.mamba_track_indices = torch.tensor([40, 41])
+ batch.mamba_track_mask = None
+
+ monkeypatch.setattr(spec_utils, "prepare_mamba_track_for_verify", prepare, raising=False)
+ draft = SimpleNamespace(bonus_tokens=torch.tensor([17, 19], dtype=torch.int32))
+ batch = SimpleNamespace(
+ spec_info=draft,
+ spec_algorithm=object(),
+ req_pool_indices=torch.tensor([0, 1]),
+ seq_lens=torch.tensor([5, 7]),
+ seq_lens_cpu=torch.tensor([5, 7]),
+ return_logprob=False,
+ tree_cache=SimpleNamespace(page_size=1),
+ mamba_track_indices=None,
+ mamba_track_mask=None,
+ )
+ seen = {}
+
+ def forward(actual, **kwargs):
+ seen["indices"], seen["mask"] = actual.mamba_track_indices, actual.mamba_track_mask
+ return SimpleNamespace(next_token_ids=torch.tensor([23, 29]))
+
+ target = SimpleNamespace(forward_batch_generation=forward)
+ plain_decode(batch, target, torch.arange(20).reshape(2, 10), track_mamba=tracking)
+ if tracking:
+ # The new lengths are 6 and 8: only the second row lands on the grid of 8, after its token is in the state.
+ assert planned == [[6, 8]]
+ assert seen["indices"].tolist() == [40, 41]
+ assert seen["mask"].tolist() == [False, True]
+ else:
+ assert planned == [] and seen == {"indices": None, "mask": None}
+
+
[email protected]("engine_tracks", [False, True])
+def test_native_decode_needs_tracking_graphs_only_with_the_radix_cache(monkeypatch, engine_tracks):
+ pytest.importorskip("sglang")
+ from sglang.srt import runtime_context
+
+ from eagle_harness.sglang import plain_decode as plain_module
+ from eagle_harness.sglang import verify_graphs
+
+ monkeypatch.setattr(verify_graphs, "native_decode_graphs", lambda: True)
+ monkeypatch.setattr(plain_module, "native_decode_tracks_mamba", lambda: engine_tracks)
+ monkeypatch.setattr(runtime_context, "get_parallel", lambda: SimpleNamespace(dp_size=1))
+ for tracking in (False, True):
+ monkeypatch.setattr(
+ runtime_context,
+ "get_exec",
+ lambda tracking=tracking: SimpleNamespace(mamba=SimpleNamespace(enable_mamba_extra_buffer=tracking)),
+ )
+ available = engine_tracks or not tracking
+ assert plain_module.native_decode_available() is available
+ assert plain_module.native_decode_blocked() is not available
+
+
[email protected]("native_route", [False, True])
[email protected]("intensity,default", [("high_intensity", 32), ("chain_intensity", 48)])
+def test_without_a_running_cap_admission_follows_memory_where_large_batches_decode_natively(
+ native_route, intensity, default
+):
+ pytest.importorskip("sglang")
+ from eagle_harness.core.config import harness_config_from_dict
+ from eagle_harness.core.limits import max_batch_size
+ from eagle_harness.sglang.algorithm import default_batch_limits
+
+ config = harness_config_from_dict({"intensity": intensity})
+ running, verify = default_batch_limits(config, native_route)
+ if native_route:
+ # The verify states cover the old default only; the engine sizes admission as without speculation.
+ assert (running, verify) == (max_batch_size(config.intensity), default)
+ else:
+ assert (running, verify) == (default, None)
+ explicit = harness_config_from_dict({"intensity": intensity, "max_verify_batch_size": 8})
+ assert default_batch_limits(explicit, native_route) == (
+ (max_batch_size(config.intensity), 8) if native_route else (8, 8)
+ )
+
+
+def test_batches_above_the_verify_limit_decode_natively_without_asking_the_policy():
+ pytest.importorskip("sglang")
+ from eagle_harness.sglang.plain_decode import NativeDecode
+
+ asked = []
+ rounds = SimpleNamespace(plain_width=lambda bs: asked.append(bs) or 4)
+ native = NativeDecode(None, None, rounds, enabled=True, verify_limit=2)
+
+ class Request:
+ pass
+
+ def batch(n):
+ return SimpleNamespace(forward_mode=SimpleNamespace(is_idle=lambda: False), reqs=[Request() for _ in range(n)])
+
+ assert not native.select(batch(2)) and asked == [2]
+ assert native.select(batch(3)) and asked == [2]
+
+
+def test_batches_above_the_verify_limit_capture_only_the_native_decode_graph():
+ pytest.importorskip("sglang")
+ from sglang.srt.model_executor.forward_batch_info import ForwardMode
+ from sglang.srt.model_executor.runner.decode_graph_variants import DecodeGraphVariant
+
+ from eagle_harness.core.limits import ComputeIntensity
+ from eagle_harness.sglang.verify_graphs import VerifyWidthGraphs
+
+ if not hasattr(DecodeGraphVariant, "forward_mode"):
+ pytest.skip("host has no per-variant forward mode")
+ graphs = VerifyWidthGraphs(ComputeIntensity.CHAIN, 8, None, plain_decode=True, max_verify_bs=8)
+ assert len(graphs.capture_variants(8)) > 1
+ (native,) = graphs.capture_variants(16)
+ assert native.forward_mode is ForwardMode.DECODE
+
+
+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
+
+ native = NativeDecode(None, None, SimpleNamespace(plain_width=lambda bs: 4), enabled=True, verify_limit=2)
+
+ class Request:
+ done = False
+
+ def finished(self):
+ return self.done
+
+ def batch(reqs):
+ return SimpleNamespace(forward_mode=SimpleNamespace(is_idle=lambda: False), reqs=reqs)
+
+ a, b, c, d, e, f = Request(), Request(), Request(), Request(), Request(), Request()
+ assert not native.skips_draft(batch([a])) and not native.skips_draft(batch([b])) # running 1, 2
+ assert native.skips_draft(batch([c])) # running 3 > 2: c is off before its first decode
+ assert native.select(batch([a, b, c]))
+ assert native.select(batch([a])) # a decoded natively above the limit: off for life
+ assert not native.skips_draft(batch([d])) # running 1 + d = 2: drafts again
+ assert not native.skips_draft(batch([d])) # d's next chunk is not counted twice
+ assert native.skips_draft(batch([c])) # a chunk of a request that is off skips at any load
+ assert not native.select(batch([d]))
+ assert native.select(batch([a, b, c])) # a burst's last decode step: every row finishes in it
+ a.done = b.done = c.done = True
+ assert not native.skips_draft(batch([e])) # the batch e joins is empty: e drafts
+ assert not native.skips_draft(batch([f])) # e + f = 2
+
+
+def test_stale_draft_kv_counts_reused_slots_the_draft_window_reads():
+ import torch
+
+ from eagle_harness.sglang.draft_kv import StaleDraftKV
+
+ req_to_token = torch.arange(1, 17).view(2, 8) # row 0: slots 1-8, row 1: slots 9-16
+ kv = StaleDraftKV(20, "cpu")
+ kv.target_only(torch.tensor([3, 4, 12]))
+ kv.drafted(torch.tensor([4])) # a later drafted write of slot 4
+ kv.reused(req_to_token, rows=[0, 1], prefix_lens=[4, 0], seq_lens=[6, 3]) # row 0 reads slots 1-4
+ assert kv._reused.tolist() == [1, 1]
+ windowed = StaleDraftKV(20, "cpu", window=3)
+ windowed.target_only(torch.tensor([3]))
+ windowed.reused(req_to_token, rows=[0], prefix_lens=[4], seq_lens=[6]) # first drafted key: position 3 (slot 4)
+ assert windowed._reused.tolist() == [0, 0]
+
+
+def test_stale_draft_kv_never_waits_for_the_gpu():
+ import torch
+
+ if not torch.cuda.is_available():
+ pytest.skip("needs a GPU")
+ from eagle_harness.sglang.draft_kv import StaleDraftKV
+
+ kv = StaleDraftKV(1 << 16, "cuda")
+ req_to_token = torch.arange(1, 1 + 4 * 512, device="cuda").view(4, 512)
+ slots = torch.arange(100, 213, device="cuda")
+ torch.cuda.synchronize()
+ torch.cuda.set_sync_debug_mode("error")
+ try:
+ kv.target_only(slots)
+ kv.drafted(slots[:8])
+ kv.reused(req_to_token, rows=[0, 1], prefix_lens=[300, 0], seq_lens=[400, 10])
+ finally:
+ torch.cuda.set_sync_debug_mode(0)
+ assert kv._reused.tolist() == [1, 105]
+
+
+def test_a_kv_only_prefill_shifts_the_ids_writes_the_draft_kv_and_relays_a_placeholder(monkeypatch):
+ pytest.importorskip("sglang.srt.speculative.eagle_info")
+ import torch
+ from sglang.srt.model_executor.forward_batch_info import ForwardBatch
+
+ from eagle_harness.sglang.draft_kv import kv_only_prefill
+
+ calls = []
+ out = SimpleNamespace(next_token_ids=torch.tensor([7, 8]), kv_loc_plan="plan",
+ logits_output=SimpleNamespace(hidden_states="target hidden"))
+
+ def forward(batch, pp_proxy_tensors=None, capture_hidden_mode=None, return_kv_loc_plan=False):
+ calls.append(("target", capture_hidden_mode.name, return_kv_loc_plan))
+ return out
+
+ def init_new(batch, runner, **kw):
+ calls.append(("draft batch", batch.spec_info.hidden_states, kw["kv_loc_plan"]))
+ return SimpleNamespace(input_ids=batch.input_ids.clone(), extend_seq_lens=torch.tensor([3, 2]))
+
+ monkeypatch.setattr(ForwardBatch, "init_new", init_new)
+ runner = SimpleNamespace(token_to_kv_pool="draft pool", model=SimpleNamespace(
+ write_prefill_kv=lambda fb, pool: calls.append(("kv", fb.input_ids.tolist(), pool))))
+ batch = SimpleNamespace(reqs=[object(), object()], seq_lens=torch.tensor([5, 9]), input_ids=torch.tensor([1, 2, 3, 4, 5]),
+ chunked_req_next_prompt_token=None, chunked_req=None)
+ result = kv_only_prefill(
+ batch, SimpleNamespace(forward_batch_generation=forward), runner, topk=4, hidden=(16, torch.bfloat16),
+ on_publish=lambda lengths: calls.append(("publish", lengths.tolist())),
+ )
+ assert calls == [("target", "FULL", True), ("publish", [5, 9]), ("draft batch", "target hidden", "plan"),
+ ("kv", [2, 3, 7, 5, 8], "draft pool")] # each position's next token; the last: sampled tokens
+ assert result is out and out.kv_loc_plan is None
+ draft = result.next_draft_input
+ assert draft.bonus_tokens is out.next_token_ids
+ assert draft.topk_p.shape == (2, 4) and draft.topk_index.shape == (2, 4) and draft.hidden_states.shape == (2, 16)
+
+
+def test_the_kv_only_pass_writes_the_keys_and_values_the_attention_would():
+ pytest.importorskip("sglang")
+ import torch
+
+ memory_pool = pytest.importorskip("sglang.srt.mem_cache.memory_pool")
+ if not hasattr(memory_pool, "KVWriteLoc"):
+ pytest.skip("engine without KV write plans")
+ from eagle_harness.sglang.models.llama_eagle4 import LlamaForCausalLMEagle4
+
+ torch.manual_seed(0)
+ heads, dim, hidden = 2, 4, 8 # MHA: q, k and v each 8 wide; the layer reads concat(embeds, hidden) = 16
+ weight = torch.randn(3 * heads * dim, 2 * hidden)
+ written = {}
+ radix = SimpleNamespace(is_cross_attention=False, k_scale=None, v_scale=None)
+ attn = SimpleNamespace(
+ qkv_proj=SimpleNamespace(weight=weight), q_size=heads * dim, kv_size=heads * dim, head_dim=dim,
+ num_kv_heads=heads, attn=radix, rotary_emb=lambda positions, q, k: (q, k + positions[:, None]),
+ )
+ layer = SimpleNamespace(input_layernorm=lambda x: x, hidden_norm=lambda x: 2 * x, attn_norm=False, self_attn=attn)
+ embeds = torch.randn(3, hidden)
+ model = SimpleNamespace(hidden_size=hidden, layers=[layer], _embed=lambda ids: embeds[ids])
+ pool = SimpleNamespace(set_kv_buffer=lambda layer, loc, k, v, ks, vs: written.update(layer=layer, loc=loc, k=k, v=v))
+ target = torch.randn(3, hidden)
+ fb = SimpleNamespace(spec_info=SimpleNamespace(hidden_states=target), input_ids=torch.tensor([2, 0, 1]),
+ positions=torch.tensor([10.0, 11.0, 12.0]),
+ out_cache_loc=torch.tensor([5, 6, 7]), out_cache_loc_is_physical=True)
+ draft = SimpleNamespace(model=model)
+ LlamaForCausalLMEagle4.write_prefill_kv(draft, fb, pool)
+ _, k, v = (torch.cat([embeds[fb.input_ids], 2 * target], -1) @ weight.T).split(heads * dim, -1)
+ assert written["layer"] is radix and torch.equal(written["loc"].loc, fb.out_cache_loc) and written["loc"].physical
+ torch.testing.assert_close(written["k"], (k + fb.positions[:, None]).view(3, heads, dim))
+ torch.testing.assert_close(written["v"], v.view(3, heads, dim))
+
+
[email protected]("skip", [True, False])
+def test_the_worker_prefill_routes_and_marks_the_written_slots(monkeypatch, skip):
+ pytest.importorskip("sglang")
+ import torch
+ from sglang.srt.model_executor.forward_batch_info import ForwardMode
+ from sglang.srt.speculative import eagle_utils
+
+ from eagle_harness.sglang import worker as module
+ from eagle_harness.sglang.draft_kv import StaleDraftKV
+
+ calls = []
+ worker = module.EagleHarnessWorker.__new__(module.EagleHarnessWorker)
+ worker._stale_kv = StaleDraftKV(16, "cpu")
+ worker._stale_kv.target_only(torch.tensor([2])) # slot 2: decoded natively earlier
+ worker._native_decode = SimpleNamespace(skips_draft=lambda batch: skip)
+ worker.req_to_token_pool = SimpleNamespace(req_to_token=torch.arange(16).view(2, 8))
+ worker.topk, worker._target_worker = 4, "target"
+ worker._draft_worker = SimpleNamespace(draft_runner="draft")
+ worker._kv_only_prefill = True
+ monkeypatch.setattr(module.EagleHarnessWorker, "_draft_context", lambda self: __import__("contextlib").nullcontext())
+ monkeypatch.setattr(eagle_utils, "get_draft_recurrent_hidden_state_spec", lambda runner: (8, torch.float32))
+ monkeypatch.setattr(module, "kv_only_prefill", lambda batch, target, runner, **kw: calls.append(("kv only", target, runner, kw["hidden"])) or "t")
+ monkeypatch.setattr(module.EAGLEWorkerV2, "forward_batch_generation", lambda self, *a: calls.append("drafted") or "d")
+ batch = SimpleNamespace(forward_mode=ForwardMode.EXTEND, is_extend_in_batch=False, return_hidden_states=False,
+ out_cache_loc=torch.tensor([4, 5]), reqs=[SimpleNamespace(multimodal_inputs=None)], prefix_lens=[4], extend_lens=[2],
+ req_pool_indices_cpu=torch.tensor([0]))
+ assert worker._prefill(batch, None, None, None) == ("t" if skip else "d")
+ assert calls == ([("kv only", "target", "draft", (8, torch.float32))] if skip else ["drafted"])
+ assert worker._stale_kv.stale[[4, 5]].tolist() == [False, False] # both routes write the draft KV
+ assert worker._stale_kv._reused.tolist() == ([0, 0] if skip else [1, 1]) # the drafted prefill read slot 2
+
+
+def test_the_prefill_reads_batch_fields_the_engine_has():
+ """The engine fields the prefill routing and the KV-only pass read (the fakes above cannot catch a renamed
+ field): ScheduleBatch, and ForwardBatch where the engine has KV write plans."""
+ pytest.importorskip("sglang")
+ import dataclasses
+
+ from sglang.srt.managers.schedule_batch import Req, ScheduleBatch
+ from sglang.srt.model_executor.forward_batch_info import ForwardBatch
+
+ from eagle_harness.sglang.draft_kv import kv_only_prefill_supported
+
+ fields = {f.name for f in dataclasses.fields(ScheduleBatch)}
+ assert {"forward_mode", "is_extend_in_batch", "return_hidden_states", "out_cache_loc", "reqs", "prefix_lens",
+ "extend_lens", "seq_lens", "input_ids", "chunked_req"} <= fields
+ assert "req_pool_indices_cpu" in fields or hasattr(Req, "req_pool_idx")
+ if kv_only_prefill_supported():
+ fb = {f.name for f in dataclasses.fields(ForwardBatch)}
+ assert {"input_ids", "extend_seq_lens", "positions", "spec_info", "out_cache_loc",
+ "out_cache_loc_is_physical"} <= fb
diff --git a/tests/test_served_chain.py b/tests/test_served_chain.py
index 2a50309..04a332c 100644
--- a/tests/test_served_chain.py
+++ b/tests/test_served_chain.py
@@ -278,6 +278,23 @@ def test_speculation_beats_native_decode_only_beyond_the_noise_of_the_two_rates(
assert _decide_width_4_or_native(clock, lambda i: 10) == 4
+def test_a_tied_comparison_with_native_decode_is_measured_again(clock):
+ """Width 4 commits 1.5 tokens per request and round. Its first 32 periods are slow and uneven (4 and 24 ms, as on a
+ cold start: no single period is a stall), which ties it with native decode's 10 ms. The comparison runs again,
+ and the clean periods that follow (10 ms) decide for speculation; a tie that persists still falls to native decode
+ (test above). Before, the first tie decided native decode for good."""
+ policy = _policy(native=True)
+ policy._pair[64] = (4, 0)
+ policy.profile = lambda: chain_rounds.AcceptProfile((0.5, 0.0, 0.0))
+ requests = _reqs(*range(64))
+ i = 0
+ while policy.exploring(64):
+ policy.round_start(64, policy.width(64), requests)
+ clock.advance((4 if i % 2 else 24) if i < 33 else 10)
+ i += 1
+ assert policy.decided[64] == 4 and policy._remeasured[64] == 1
+
+
def _tree(tmp_path=None, key=None, writer=True, sync=lambda step: step, native_us=None):
return ServedTreePolicy(
16,
diff --git a/tests/test_sglang_overlap.py b/tests/test_sglang_overlap.py
index 393326d..26bed38 100644
--- a/tests/test_sglang_overlap.py
+++ b/tests/test_sglang_overlap.py
@@ -45,6 +45,7 @@ def test_decode_handoff_uses_the_scheduler_stream_contract(monkeypatch, overlap)
_verified=SimpleNamespace(record=lambda: calls.append("verified")),
_chain_rounds=ChainRounds(None, None, lambda batch: 10),
_native_decode=SimpleNamespace(select=lambda batch: False),
+ _stale_kv=None,
)
monkeypatch.setattr(module, "spec_stage_span", lambda name: nullcontext())
monkeypatch.setattr(module, "spin_wait", lambda event: calls.append("wait"))
diff --git a/tests/test_sglang_plugin.py b/tests/test_sglang_plugin.py
index a3fb3de..dbfbbe9 100644
--- a/tests/test_sglang_plugin.py
+++ b/tests/test_sglang_plugin.py
@@ -147,12 +147,18 @@ def test_plugin_registers_the_draft_model(registered):
# ------------------------------------------------------- H11 + server args
@pytest.mark.parametrize("overlap_off", [False, True])
def test_server_args_accept_eagle_harness_and_config(registered, overlap_off):
+ from eagle_harness.sglang.plain_decode import verify_limit_supported
+
args = _server_args(disable_overlap_schedule=overlap_off)
handle_speculative_decoding(args)
assert resolution_result(args, "speculative_algorithm") == ALGORITHM_NAME
assert resolution_result(args, "disable_overlap_schedule") is overlap_off
assert resolution_result(args, "scheduler_recv_interval") == 4
- assert resolution_result(args, "max_running_requests") == 32
+ # Native decoding separates admission from the memory-conservative verify limit.
+ native_route = verify_limit_supported()
+ assert resolution_result(args, "max_running_requests") == (512 if native_route else 32)
+ config = parse_harness_config(resolution_result(args, "speculative_algorithm_config"))
+ assert config.max_verify_batch_size == (32 if native_route else None)
assert resolution_result(args, "enable_mixed_chunk") is False
diff --git a/tests/test_tokenspeed_adapter.py b/tests/test_tokenspeed_adapter.py
index 9fa976c..7425953 100644
--- a/tests/test_tokenspeed_adapter.py
+++ b/tests/test_tokenspeed_adapter.py
@@ -53,9 +53,29 @@ def test_serve_uses_device_policy_with_calibration():
assert config.mode is Mode.SERVE and config.cost_dir == "/calibration/cost"
-def test_unsupported_cost_model_modes_are_refused():
- with pytest.raises(NotImplementedError, match="static and serve"):
- parse_algorithm_config({"mode": "calibrate", "data_path": "/nonexistent"})
[email protected]("sampled", [False, True])
+def test_sampled_proposals_are_explicit_harness_configuration(sampled):
+ config = parse_algorithm_config({"mode": "serve", "data_path": "/calibration", "sampled_proposals": sampled})
+ assert config.sampled_proposals is sampled
+ assert not parse_algorithm_config({"mode": "static"}).sampled_proposals
+
+
[email protected]("value", [None, 1, "true"])
+def test_sampled_proposals_rejects_non_boolean_values(value):
+ with pytest.raises(ValueError, match="sampled_proposals must be a boolean"):
+ parse_algorithm_config({"mode": "serve", "data_path": "/calibration", "sampled_proposals": value})
+
+
[email protected]("mode", ["static", "calibrate"])
+def test_sampled_proposals_requires_serve_mode(mode):
+ with pytest.raises(ValueError, match="sampled_proposals requires serve mode"):
+ parse_algorithm_config({"mode": mode, "data_path": "/calibration", "sampled_proposals": True})
+
+
+def test_calibrate_mode_needs_an_output_directory():
+ assert parse_algorithm_config({"mode": "calibrate", "data_path": "/nonexistent"}).mode is Mode.CALIBRATE
+ with pytest.raises(ValueError, match="data_path"):
+ parse_algorithm_config({"mode": "calibrate"})
@pytest.mark.parametrize(
@@ -197,8 +217,8 @@ def test_capability_contract_registers_with_every_capability(fake_plugins):
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"]
+ fake_plugins.PLUGIN_CAPABILITIES = hooks.REQUIRED_CAPABILITIES - {"drafter.round_protocol"}
+ assert hooks.hook_problems() == ["PLUGIN_CAPABILITIES lacks drafter.round_protocol"]
def test_capability_contract_refuses_a_breaking_api_version(fake_plugins):
@@ -225,8 +245,8 @@ def test_release_contract_refuses_an_older_api_version(fake_plugins):
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
+ assert set(hooks.PUBLIC_POLICY[1:]) <= capability and not set(hooks.RELEASE_POLICY) & capability
+ assert set(hooks.RELEASE_POLICY[1:]) <= release and not set(hooks.PUBLIC_POLICY) & release
def test_the_drafter_aliases_every_release_name_to_its_public_policy():
diff --git a/tests/test_tokenspeed_calibration.py b/tests/test_tokenspeed_calibration.py
new file mode 100644
index 0000000..684b203
--- /dev/null
+++ b/tests/test_tokenspeed_calibration.py
@@ -0,0 +1,223 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""CPU calibration policy and fake-engine measurement-to-serving tests."""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+from eagle_harness.core.calibration import (
+ AttentionShape,
+ CalibrationPaths,
+ MeasureParams,
+ MeasureRecord,
+ save_model_timings,
+)
+from eagle_harness.core.config import Mode, build_cost_model
+from eagle_harness.core.cost_table import load_cost_tables
+from eagle_harness.core.limits import ComputeIntensity, draft_query_lens, verify_buckets
+from eagle_harness.tokenspeed.config import parse_algorithm_config
+from eagle_harness.tokenspeed.measure_run import attention_config, measure_batch
+from eagle_harness.tokenspeed.measurement import MeasurePolicy
+
+
[email protected]("intensity,topk", [(ComputeIntensity.HIGH, 4), (ComputeIntensity.LOW, 8), (ComputeIntensity.CHAIN, 1)])
+def test_measure_policy_sweeps_core_widths_without_reading_costs(intensity, topk):
+ policy = MeasurePolicy(verify_num=16, node_top_k=topk, tree_depth=5,
+ compute_intensity=intensity.value, device=torch.device("cpu"))
+ drafts, verifies = set(), set()
+ for _ in range(120):
+ policy.next_widths(8, 8)
+ policy.write_round()
+ drafts.add(policy.draft_width)
+ verifies.add(policy.verify_width_now)
+ assert policy.widths[1].item() == policy.previous_draft_width
+ assert policy.widths[2].item() == policy.draft_width
+ assert all(policy.go_ready(d, 12) for d in range(1, 5))
+ assert not policy.go_ready(5, 12)
+ assert drafts == set(w for w in draft_query_lens(8, intensity) if w <= topk)
+ assert verifies == set(w for w in verify_buckets(8, intensity) if w <= 16)
+
+
+class FakeEngine:
+ """Emits known stage timings at the public driver/engine boundary."""
+
+ def __init__(self, args):
+ self.args = args
+ self.batches = []
+
+ def generate(self, *, input_ids, sampling_params):
+ args = self.args
+ bs = len(input_ids)
+ self.batches.append(bs)
+ assert sampling_params["ignore_eos"]
+ assert sampling_params["max_new_tokens"] > 512
+ paths = CalibrationPaths(args.run_dir)
+ with open(paths.config + "/measure_config.json") as f:
+ assert json.load(f)["batch_size"] == bs
+ records = []
+ intensity = ComputeIntensity(args.compute_intensity)
+ for model, widths, fixed, layers in (
+ ("slm", draft_query_lens(bs, intensity), 100, 1),
+ ("llm", verify_buckets(bs, intensity), 1000, 4),
+ ):
+ for q in widths:
+ if q > (args.topk if model == "slm" else args.num_draft_tokens):
+ continue
+ for length in range(64, 512):
+ us = fixed + q * bs + layers * (10 + length / 1000) + (length % 3) / 10
+ records.append(MeasureRecord(int(us * 1000), 1000, q, length, f"model_{model}", bs))
+ save_model_timings(paths, MeasureParams(64, 2048, bs, 16, 4, 16, 1), records)
+
+
+def fake_attention(**kwargs):
+ return [MeasureRecord(int((10 + length / 1000) * 1000), 1000, width, length,
+ kwargs["category"], kwargs["batch_size"])
+ for width in kwargs["widths"] for length in range(64, 2048, 4)]
+
+
+def test_fake_engine_calibrates_every_served_batch_and_loads_profile(tmp_path):
+ args = SimpleNamespace(run_dir=str(tmp_path), compute_intensity="high_intensity", context_step=64,
+ context_stop=2048, num_draft_tokens=16, topk=4, num_steps=5, fast=True, tp_size=4)
+ engine = FakeEngine(args)
+ target = SimpleNamespace(num_attention_heads=16, num_key_value_heads=4, head_dim=64, num_hidden_layers=4)
+ draft = SimpleNamespace(num_attention_heads=16, num_key_value_heads=4, head_dim=64, num_hidden_layers=1)
+ for bs in range(1, 33):
+ assert measure_batch(args, engine, [1, 2, 3], bs, target, draft, attention_samples=fake_attention)
+ assert engine.batches == list(range(1, 33))
+ tables = load_cost_tables(str(tmp_path / "cost"))
+ assert set(tables) == set(range(1, 33))
+ for bs, table in tables.items():
+ for interval in table.intervals:
+ assert interval.draft.index == (0, 1, 3)
+ assert interval.target.index == tuple(sorted(w - 1 for w in verify_buckets(bs, ComputeIntensity.HIGH) if w <= 16))
+ assert all(v > 0 for v in (*interval.draft.value, *interval.target.value))
+ config = parse_algorithm_config({"mode": "serve", "data_path": str(tmp_path)})
+ assert config.mode is Mode.SERVE
+ model = build_cost_model(config, node_top_k=4, tree_depth=5, verify_num=16, target_is_moe=False)
+ assert model is not None
+
+
+def test_short_engine_run_cannot_reuse_old_samples(tmp_path):
+ args = SimpleNamespace(run_dir=str(tmp_path), compute_intensity="high_intensity", context_step=64,
+ context_stop=2048, num_draft_tokens=16, topk=4, num_steps=5, fast=True, tp_size=4)
+ target = SimpleNamespace(num_attention_heads=16, num_key_value_heads=4, head_dim=64, num_hidden_layers=4)
+ engine = FakeEngine(args)
+ measure_batch(args, engine, [1], 1, target, target, attention_samples=fake_attention)
+ with pytest.raises(FileNotFoundError):
+ measure_batch(args, SimpleNamespace(generate=lambda **kw: None), [1], 1, target, target,
+ attention_samples=fake_attention)
+
+
+def test_hybrid_attention_layer_ids_win_over_block_names():
+ config = SimpleNamespace(num_attention_heads=16, num_key_value_heads=4, head_dim=64,
+ num_hidden_layers=8, full_attention_layer_ids=[2, 6], layer_types=["attention"] * 8)
+ assert attention_config(config)[1].attention_layers == 2
+
+
+def test_sliding_window_draft_is_measured_with_its_window():
+ # The released Qwen3.8 EAGLE-4 head: one sliding-window layer, no full-attention layer.
+ draft = SimpleNamespace(num_attention_heads=40, num_key_value_heads=40, head_dim=128, num_hidden_layers=1,
+ layer_types=["sliding_attention"], sliding_window=4096, use_sliding_window=True)
+ assert attention_config(draft) == ((40, 40, 128, 4096), AttentionShape(1, 1, 4096))
+
+
+def test_hybrid_target_measures_full_attention_without_a_window():
+ target = SimpleNamespace(text_config=SimpleNamespace(
+ num_attention_heads=24, num_key_value_heads=4, head_dim=256, num_hidden_layers=4, sliding_window=None,
+ layer_types=["linear_attention"] * 3 + ["full_attention"]))
+ assert attention_config(target) == ((24, 4, 256, 0), AttentionShape(1))
+
+
+def test_mixed_full_and_sliding_layers_are_refused():
+ config = SimpleNamespace(num_attention_heads=8, num_key_value_heads=8, head_dim=64, num_hidden_layers=2,
+ layer_types=["full_attention", "sliding_attention"], sliding_window=1024)
+ with pytest.raises(ValueError, match="mixed"):
+ attention_config(config)
+
+
+def test_cli_serializes_plugin_config_for_engine(tmp_path, monkeypatch):
+ import sys
+
+ from eagle_harness.tokenspeed import measure_run
+
+ seen = {}
+
+ class Engine:
+ def __init__(self, **kwargs):
+ # The engine's ServerArgs parser accepts JSON text, not a dict.
+ seen.update(kwargs)
+ seen["parsed_config"] = json.loads(kwargs["speculative_algorithm_config"])
+
+ def shutdown(self):
+ seen["shutdown"] = True
+
+ monkeypatch.setitem(sys.modules, "tokenspeed.runtime.configs.model_config",
+ SimpleNamespace(get_hf_text_config=lambda config: config))
+ monkeypatch.setitem(sys.modules, "tokenspeed.runtime.entrypoints.engine", SimpleNamespace(Engine=Engine))
+ monkeypatch.setitem(sys.modules, "tokenspeed.runtime.utils.hf_transformers_utils",
+ SimpleNamespace(get_config=lambda *a, **kw: object()))
+ monkeypatch.setitem(sys.modules, "transformers", SimpleNamespace(
+ AutoConfig=SimpleNamespace(from_pretrained=lambda *a, **kw: object()),
+ AutoTokenizer=SimpleNamespace(from_pretrained=lambda *a, **kw: lambda *a, **kw: {"input_ids": [1, 2, 3]}),
+ ))
+ monkeypatch.setattr(measure_run, "measure_batch", lambda *a, **kw: True)
+ measure_run.main(["--model", "target", "--draft-model", "draft", "--run-dir", str(tmp_path),
+ "--tp-size", "4", "--compute-intensity", "high_intensity", "--topk", "4",
+ "--num-steps", "5", "--num-draft-tokens", "16", "--max-bs", "1",
+ "--mamba-ssm-dtype", "float32"])
+ assert seen["parsed_config"] == {"mode": "calibrate", "data_path": str(tmp_path),
+ "intensity": "high_intensity"}
+ assert seen["shutdown"]
+
+
+def test_recorder_pairs_next_verify_and_writes_only_complete_rank_zero_batch(tmp_path, monkeypatch):
+ from eagle_harness.tokenspeed.measurement import CostMeasurement, MEASURED_ROUNDS
+
+ class Event:
+ def __init__(self, **kwargs):
+ pass
+
+ def record(self):
+ pass
+
+ def synchronize(self):
+ pass
+
+ def elapsed_time(self, other):
+ return 1.25
+
+ monkeypatch.setattr(torch.cuda, "Event", Event)
+ monkeypatch.setattr(torch.cuda, "synchronize", lambda: None)
+ paths = CalibrationPaths(str(tmp_path))
+ paths.write_measure_params(MeasureParams(64, 2048, 2, 16, 4, 16, 8))
+ for rank in (0, 1):
+ recorder = CostMeasurement(run_dir=str(tmp_path), tree_depth=5, tp_group=None,
+ rank=rank, device=torch.device("cpu"))
+ recorder.on_extend()
+ recorder.record_verify(2)
+ assert recorder.verify_rounds == 0
+ recorder.end_draft(1, 4, 16, 100)
+ assert recorder.pending_verify is None
+ for i in range(MEASURED_ROUNDS):
+ recorder.begin_draft()
+ recorder.end_draft(2, 4, 16, 100 + i)
+ recorder.record_verify(2)
+ assert recorder.finished
+ assert recorder.complete() is (rank == 0)
+ if rank == 0:
+ assert len(recorder.records) == 2 * MEASURED_ROUNDS
+ assert recorder.records[-1].query_length == 16
+ assert recorder.records[-1].cache_length == 100 + MEASURED_ROUNDS - 1
+ assert recorder.records[0].measure_count == 4
+ recorder.write_model_records()
+ assert not recorder.complete()
+ else:
+ assert recorder.records == []
+ recorder.on_extend()
+ assert not recorder.finished and recorder.pending_verify is None
diff --git a/tests/test_tokenspeed_ownership.py b/tests/test_tokenspeed_ownership.py
index 0dbe919..6d2a6ab 100644
--- a/tests/test_tokenspeed_ownership.py
+++ b/tests/test_tokenspeed_ownership.py
@@ -1,7 +1,7 @@
# Copyright 2026 Eagle AI Corp.
# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
-"""Partner runtime code is an installed engine dependency, not vendored here."""
+"""EAGLE-specific TokenSpeed-port code is owned and shipped by the harness."""
import re
from pathlib import Path
@@ -14,4 +14,47 @@ def test_no_tokenspeed_copyright_code_in_harness():
for path in package.rglob("*")
if path.suffix in {".py", ".cu", ".h"} and re.search(r"Copyright[^\n]*LightSeek", path.read_text())
]
- assert not copied, f"TokenSpeed-owned sources belong in the engine: {copied}"
+ assert not copied, f"Eagle-owned adapter sources must carry the Eagle license: {copied}"
+
+
+def test_adapter_does_not_import_engine_owned_round_implementations():
+ import ast
+
+ package = Path(__file__).resolve().parents[1] / "eagle_harness" / "tokenspeed"
+ forbidden = (
+ "tokenspeed.runtime.execution.drafter.tree_round",
+ "tokenspeed.runtime.execution.drafter.eagle_harness",
+ )
+ for path in package.rglob("*.py"):
+ tree = ast.parse(path.read_text())
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ImportFrom):
+ assert not (node.module or "").startswith(forbidden), path
+ elif isinstance(node, ast.Import):
+ assert not any(alias.name.startswith(forbidden) for alias in node.names), path
+
+
+def test_generic_hook_registration_does_not_require_harness_implementation():
+ from eagle_harness.tokenspeed.hooks import CAPABILITY_HOOKS, HOOKS, REQUIRED_CAPABILITIES
+
+ assert REQUIRED_CAPABILITIES == {
+ "drafter.algorithm_config", "drafter.aux_hidden_capture", "drafter.tree_layout",
+ "attention.windowed_tree_lanes", "drafter.round_protocol", "drafter.tree_lanes", "drafter.tree_policy",
+ "sampling.tree_sampler",
+ }
+ assert not any("tree_round" in hook.path for hook in HOOKS + CAPABILITY_HOOKS)
+
+
+def test_owned_round_sources_keep_eagle_headers_and_ship_cuda_sources():
+ from eagle_harness.tokenspeed.tree_round.ops import build
+
+ root = Path(build.__file__).parents[1]
+ for path in root.rglob("*"):
+ if path.suffix not in {".py", ".cu"}:
+ continue
+ text = path.read_text()
+ assert "Copyright 2026 Eagle AI Corp." in text.splitlines()[0], path
+ assert "SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available" in text.splitlines()[1], path
+ for name in build.MODULES:
+ assert (build.SOURCE / f"eagle_harness_{name}.cu").is_file()
+ assert (build.SOURCE / "tvm_ffi_utils.h").is_file()
diff --git a/tests/test_tokenspeed_plugin.py b/tests/test_tokenspeed_plugin.py
index 324c8e9..6a6395e 100755
--- a/tests/test_tokenspeed_plugin.py
+++ b/tests/test_tokenspeed_plugin.py
@@ -20,15 +20,15 @@ try:
except (ImportError, RuntimeError) as exc: # RuntimeError: tokenspeed-kernel on a host without a GPU
pytest.skip(f"TokenSpeed is not importable here: {exc}", allow_module_level=True)
-from tokenspeed.runtime.configs.model_profile import ModelProfile # noqa: E402
-from tokenspeed.runtime.execution import drafter as drafter_registry # noqa: E402
-from tokenspeed.runtime.plugins import registry # noqa: E402
+from tokenspeed.runtime.configs.model_profile import ModelProfile
+from tokenspeed.runtime.execution import drafter as drafter_registry
+from tokenspeed.runtime.plugins import registry
-from eagle_harness import compat # noqa: E402
-from eagle_harness.models.eagle4_config import EAGLE4_ARCH # noqa: E402
-from eagle_harness.tokenspeed import plugin # noqa: E402
-from eagle_harness.tokenspeed.config import ALGORITHM_NAME # noqa: E402
-from eagle_harness.tokenspeed.hooks import hook_problems # noqa: E402
+from eagle_harness import compat
+from eagle_harness.models.eagle4_config import EAGLE4_ARCH
+from eagle_harness.tokenspeed import plugin
+from eagle_harness.tokenspeed.config import ALGORITHM_NAME
+from eagle_harness.tokenspeed.hooks import hook_problems
HAS_HOOKS = not hook_problems()
needs_hooks = pytest.mark.skipif(
@@ -76,15 +76,15 @@ def test_draft_profile_is_a_valid_mha_profile():
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
+ from eagle_harness.tokenspeed.tree_round.dynamic import DynamicDrafter
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)
+ assert hasattr(DynamicDrafter, "round_candidates")
for name in names[1:]:
assert getattr(HarnessDrafter, name) is not getattr(Eagle, name)
@@ -94,9 +94,8 @@ 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
+ from eagle_harness.tokenspeed.tree_round.dynamic import DynamicDrafter
monkeypatch.setattr(DynamicDrafter, "wire_target", lambda self, target: None)
drafter = HarnessDrafter.__new__(HarnessDrafter)
@@ -104,6 +103,35 @@ def test_a_wrapped_moe_target_is_moe(monkeypatch):
assert drafter._target_is_moe is True
+@needs_hooks
[email protected]("tp_size", [1, 4])
+def test_calibration_uses_the_engine_device_process_group(tp_size, tmp_path, monkeypatch):
+ from types import SimpleNamespace
+
+ import torch
+ from tokenspeed.runtime.distributed import process_group_manager as groups
+
+ from eagle_harness.tokenspeed.config import parse_algorithm_config
+ from eagle_harness.tokenspeed.drafter import HarnessDrafter
+ from eagle_harness.tokenspeed.measurement import MeasurePolicy
+
+ manager = groups.ProcessGroupManager()
+ ranks, process_group = tuple(range(tp_size)), object()
+ manager.register_process_group("nccl", ranks, process_group)
+ monkeypatch.setattr(groups, "process_group_manager", manager)
+ monkeypatch.setattr(torch.cuda, "Event", lambda **kwargs: object())
+ drafter = HarnessDrafter.__new__(HarnessDrafter)
+ drafter.device = torch.device("cpu")
+ drafter.config = parse_algorithm_config({"mode": "calibrate", "data_path": str(tmp_path)})
+ drafter.draft_model_runner = SimpleNamespace(mapping=SimpleNamespace(
+ rank=0, attn=SimpleNamespace(tp_size=tp_size, tp_group=ranks)))
+
+ policy = drafter._make_policy(16, 4, 5)
+
+ assert isinstance(policy, MeasurePolicy)
+ assert drafter.measurement.tp_group is (process_group if tp_size > 1 else None)
+
+
@needs_hooks
def test_compat_reports_the_hooks_ok():
assert compat.check("tokenspeed").ok
diff --git a/tests/test_tokenspeed_policy_cost.py b/tests/test_tokenspeed_policy_cost.py
index ef5e407..dc8b84c 100644
--- a/tests/test_tokenspeed_policy_cost.py
+++ b/tests/test_tokenspeed_policy_cost.py
@@ -14,10 +14,8 @@ from eagle_harness.core.cost_model import CostModel, CostModelParams, SizeClass
from eagle_harness.core.cost_table import BatchCostTable, CostCurve, IntervalCost, load_cost_tables
from eagle_harness.core.limits import ComputeIntensity
from eagle_harness.tokenspeed.costs import tree_policy_costs
-
-pytest.importorskip("tokenspeed.runtime.execution.drafter.tree_round.device_policy")
-from tokenspeed.runtime.execution.drafter.tree_round.device_policy import DevicePolicy, write_round_slots
-from tokenspeed.runtime.execution.drafter.tree_round.policy_cost import build_tables
+from eagle_harness.tokenspeed.tree_round.device_policy import DevicePolicy, write_round_slots
+from eagle_harness.tokenspeed.tree_round.policy_cost import build_tables
def cost_fixture():
diff --git a/tests/test_tokenspeed_policy_golden.py b/tests/test_tokenspeed_policy_golden.py
index b680a15..69adbcb 100644
--- a/tests/test_tokenspeed_policy_golden.py
+++ b/tests/test_tokenspeed_policy_golden.py
@@ -41,8 +41,7 @@ def golden_tables(golden, tmp_path_factory):
@pytest.fixture(scope="module")
def engine_policy():
- pytest.importorskip("tokenspeed")
- from tokenspeed.runtime.execution.drafter.tree_round import device_policy
+ from eagle_harness.tokenspeed.tree_round import device_policy
return device_policy
@@ -107,7 +106,7 @@ def test_golden_nonlagged_scores_round_trip(golden, golden_tables, flat):
@pytest.mark.parametrize("case_index", range(3), ids=["serving-k4", "serving-k6", "serving-k8"])
def test_engine_packs_golden_costs_exactly(golden, golden_tables, engine_policy, case_index):
- from tokenspeed.runtime.execution.drafter.tree_round.policy_cost import build_tables
+ from eagle_harness.tokenspeed.tree_round.policy_cost import build_tables
case = golden["decisions_high_intensity"][case_index]
costs = tree_policy_costs(_model(golden_tables, case))
diff --git a/tests/test_tree_step_gpu.py b/tests/test_tree_step_gpu.py
index f3c5f53..da96246 100644
--- a/tests/test_tree_step_gpu.py
+++ b/tests/test_tree_step_gpu.py
@@ -105,3 +105,49 @@ def test_rank_and_select_kernels_match_reference(k, depth, bs, count, width):
index = torch.sort(want_ranked[:, : width - 1], dim=-1).values
assert torch.equal(got.top_scores_index, index)
assert torch.equal(got.draft_tokens, torch.gather(tree.tokens[:bs], 1, index))
+
+
+_STEP_AT_FULL_BATCH = """
+import torch
+from eagle_harness.core.draft_tree import DraftTree, TreeShape
+
+k, depth, bs, h = {k}, 4, 32, 256
+tree = DraftTree(TreeShape(k, depth, work_cap=64), bs, h, torch.bfloat16, torch.device("cuda"), max_verify=32)
+tree.stage_root(bs, torch.rand(bs, k, device="cuda").softmax(-1), torch.zeros(bs, k, dtype=torch.int64,
+ device="cuda"), torch.zeros(bs, h, device="cuda", dtype=torch.bfloat16))
+tree.begin(bs)
+tree.set_step_slots(bs, 1, torch.zeros(bs, k, dtype=torch.int64, device="cuda"))
+p = torch.rand(bs * k, k, device="cuda").softmax(-1).sort(-1, descending=True).values
+tree.step(bs, 1, p, torch.zeros(bs * k, k, dtype=torch.int64, device="cuda"),
+ torch.zeros(bs * k, h, device="cuda", dtype=torch.bfloat16))
+torch.cuda.synchronize()
+"""
+
+
[email protected]("k", [2, 4, 8])
+def test_tree_step_work_deltas_read_only_their_rows_layer_scores(tmp_path, k):
+ """The step's work-delta merge loaded next_pow2(K + 1) - 1 layer scores per row, past the row's K: the last row
+ of a full batch read past ``layer_top``, an illegal address where that tensor ended its allocation (one GPU,
+ batch size 32, --disable-radix-cache, at startup). compute-sanitizer reports any such read."""
+ import os
+ import shutil
+ import subprocess
+ import sys
+
+ sanitizer = shutil.which("compute-sanitizer") or os.path.join(
+ os.environ.get("CUDA_HOME", "/usr/local/cuda"), "bin", "compute-sanitizer"
+ )
+ if not os.path.exists(sanitizer):
+ pytest.skip("needs compute-sanitizer")
+ script = tmp_path / "step.py"
+ script.write_text(_STEP_AT_FULL_BATCH.format(k=k))
+ run = subprocess.run(
+ [sanitizer, "--tool", "memcheck", "--error-exitcode", "3", sys.executable, str(script)],
+ capture_output=True,
+ text=True,
+ timeout=900,
+ check=False,
+ # One cudaMalloc per tensor, so the sanitizer sees each tensor's own bounds.
+ env=dict(os.environ, PYTORCH_NO_CUDA_MEMORY_CACHING="1"),
+ )
+ assert run.returncode == 0, run.stdout[-3000:] + run.stderr[-2000:]
diff --git a/tests/test_worker_rounds.py b/tests/test_worker_rounds.py
index 7ff5aa8..1cfc457 100644
--- a/tests/test_worker_rounds.py
+++ b/tests/test_worker_rounds.py
@@ -82,7 +82,9 @@ def modules(monkeypatch):
stub("sglang.srt.model_executor.cuda_graph_config", Backend=object, Phase=object, check_cuda_graph_backend=object)
stub("sglang.srt.model_executor.runner", get_batch_sizes_to_capture=lambda runner: ([1, 8], None))
stub(
- "sglang.srt.runtime_context", **dict.fromkeys(("get_exec", "get_model", "get_parallel", "get_schedule", "get_spec"), object)
+ "sglang.srt.runtime_context",
+ **dict.fromkeys(("get_model", "get_parallel", "get_schedule", "get_spec"), object),
+ get_exec=lambda: SimpleNamespace(mamba=SimpleNamespace(enable_mamba_extra_buffer=False)),
)
stub("sglang.srt.speculative.draft_utils", DraftBackendFactory=object)
stub("sglang.srt.speculative.eagle_utils", default_tree_mask_mode=object)
@@ -405,6 +407,7 @@ def test_attention_initialization_wires_the_same_width_plan_into_both_routes(mod
intensity=module.ComputeIntensity.CHAIN,
data_path=None if kind == "served" else str(tmp_path),
cost_cache_dir=str(tmp_path),
+ max_verify_batch_size=None,
)
worker._chain_schedule = [(1, 1, 4), (2, 8, 0)] if kind == "schedule" else None
worker._served_chain = kind == "served"
@@ -455,7 +458,7 @@ def test_packaged_choices_look_up_this_servers_setup(modules, monkeypatch):
@pytest.mark.parametrize("dp_size,tracking", [(2, False), (1, True), (2, True)])
-def test_native_decode_still_rejects_dp_and_mamba_tracking(modules, monkeypatch, dp_size, tracking):
+def test_native_decode_still_rejects_dp_and_untracked_mamba_states(modules, monkeypatch, dp_size, tracking):
module = modules.worker
spec = SimpleNamespace(
speculative_algorithm_config="{}",
@@ -471,6 +474,7 @@ def test_native_decode_still_rejects_dp_and_mamba_tracking(modules, monkeypatch,
module, "get_exec", lambda: SimpleNamespace(mamba=SimpleNamespace(enable_mamba_extra_buffer=tracking))
)
monkeypatch.setattr(module, "get_parallel", lambda: SimpleNamespace(dp_size=dp_size))
+ monkeypatch.setattr(module, "native_decode_tracks_mamba", lambda: False)
target = SimpleNamespace(model_runner=SimpleNamespace(model_config=object()))
- with pytest.raises(ValueError, match="requires DP1 and disabled Mamba prefix-cache tracking"):
+ with pytest.raises(ValueError, match="requires DP1 and, with Mamba prefix-cache tracking, an engine whose native"):
module.EagleHarnessWorker(None, 0, 0, target)
diff --git a/tests/tokenspeed_round/__init__.py b/tests/tokenspeed_round/__init__.py
new file mode 100644
index 0000000..25e9362
--- /dev/null
+++ b/tests/tokenspeed_round/__init__.py
@@ -0,0 +1,2 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
diff --git a/tests/tokenspeed_round/chain_core_costs.py b/tests/tokenspeed_round/chain_core_costs.py
new file mode 100644
index 0000000..6a1e7d2
--- /dev/null
+++ b/tests/tokenspeed_round/chain_core_costs.py
@@ -0,0 +1,38 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Integration fixture for the optional installed core cost model."""
+
+
+def model(depth=15, verify=16, *, custom=False):
+ import pytest
+
+ pytest.importorskip("eagle_harness")
+ from eagle_harness.core.cost_model import ChainCoef, CostModel, CostModelParams
+ from eagle_harness.core.cost_table import BatchCostTable, CostCurve, IntervalCost
+ from eagle_harness.core.limits import ComputeIntensity
+
+ index = (0, 1, 3, 5, 7, 9, 11, 13, 15)
+ ratios = (
+ (1.0, 1.3, 1.4, 2.5, 2.51, 2.6, 2.7, 2.8, 2.9),
+ (1.0, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4),
+ )
+ draft = CostCurve((10.0,), (1.0,), (0,), (), ())
+ intervals = tuple(
+ IntervalCost(CostCurve(tuple(100 * r for r in row), row, index, (), ()), draft)
+ for row in ratios
+ )
+ # Live batches 1..512 share one measurement, but still have different tiers.
+ table = BatchCostTable(4, 1024, 1024, 16, 4096, 1, intervals, (17.0, 29.0))
+ params = (
+ CostModelParams(
+ chain_coef=tuple(ChainCoef(t, 0.125, 0.5) for t in (1.0, 2.0, 3.0, 4.0)),
+ chain_ref_cost=3.0,
+ chain_cliff_min_cost=0.25,
+ chain_cliff_ratio=2.0,
+ chain_tiny_max_bs=1,
+ )
+ if custom
+ else CostModelParams()
+ )
+ return CostModel({4: table}, params, ComputeIntensity.CHAIN, 1, depth, verify)
diff --git a/tests/tokenspeed_round/chain_cost_records.py b/tests/tokenspeed_round/chain_cost_records.py
new file mode 100644
index 0000000..1acf4bb
--- /dev/null
+++ b/tests/tokenspeed_round/chain_cost_records.py
@@ -0,0 +1,55 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Structural chain records; values are intentionally distinct, not a cost model."""
+
+from dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class StopTerms:
+ gain_scale: float
+ cost: float
+ threshold: float
+ cliff_gain_scale: float
+ cliff_cost: float
+
+
+@dataclass(frozen=True)
+class BatchCosts:
+ cache_length_step: int
+ intervals: tuple[tuple[StopTerms, ...], ...]
+
+
+@dataclass(frozen=True)
+class PolicyCosts:
+ batches: tuple[BatchCosts, ...]
+
+
+def records(depth: int = 7) -> PolicyCosts:
+ zero = StopTerms(0.0, 0.0, 0.0, 0.0, 0.0)
+ return PolicyCosts(
+ tuple(
+ BatchCosts(
+ 512 if live % 2 else 1024,
+ tuple(
+ tuple(
+ (
+ StopTerms(
+ 1.123456789012345 + d,
+ 0.25 + live,
+ 1.5 + interval,
+ 2.123456789012345 + d,
+ 0.5 + live,
+ )
+ if d >= 2 and d % 2 == 0 and d < depth - 1
+ else zero
+ )
+ for d in range(depth)
+ )
+ for interval in range(1 + live % 2)
+ ),
+ )
+ for live in range(1, 513)
+ )
+ )
diff --git a/tests/tokenspeed_round/core_costs.py b/tests/tokenspeed_round/core_costs.py
new file mode 100644
index 0000000..ff0a9e3
--- /dev/null
+++ b/tests/tokenspeed_round/core_costs.py
@@ -0,0 +1,59 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Optional integration fixtures using the installed adapter's shared core."""
+
+import pytest
+
+pytest.importorskip("eagle_harness")
+
+from eagle_harness.core.cost_model import CostModel, CostModelParams, depth_loss_ratio
+from eagle_harness.core.cost_table import BatchCostTable, CostCurve, IntervalCost
+from eagle_harness.core.limits import ComputeIntensity
+
+
+def cost_fixture():
+ """Different measured tiers, context intervals and model ratios."""
+ tables = {}
+ for bs, slope in ((1, 0.03), (4, 0.07), (8, 0.13), (32, 0.2)):
+ intervals = []
+ ratios = []
+ for interval in range(2):
+ index = (0, 1, 3, 7, 15, 31, 63)
+ target = CostCurve(
+ (100.0,) * len(index),
+ tuple(1 + i * slope * (1 + 0.1 * interval) for i in index),
+ index,
+ (),
+ (),
+ )
+ draft = CostCurve((10.0,) * 4, (1.0, 1.1, 1.2, 1.4), (0, 1, 3, 7), (), ())
+ intervals.append(IntervalCost(target, draft))
+ ratios.append(10.0 + interval * 10)
+ tables[bs] = BatchCostTable(
+ bs, 1024, 1024, 64, 64, 8, tuple(intervals), tuple(ratios)
+ )
+ return tables
+
+
+def policy_costs(
+ costs, *, k, depth, verify, moe, intensity="high_intensity", async_layer_ratio=0.9
+):
+ intensity = ComputeIntensity(intensity)
+ model = CostModel(
+ costs,
+ CostModelParams(
+ depth_loss_ratio=depth_loss_ratio(
+ "eagle4", target_is_moe=moe, intensity=intensity
+ ),
+ async_layer_ratio=async_layer_ratio,
+ ),
+ intensity,
+ k,
+ depth,
+ verify,
+ moe,
+ )
+ from eagle_harness.tokenspeed.costs import tree_policy_costs
+
+ return tree_policy_costs(model)
diff --git a/tests/tokenspeed_round/cost_records.py b/tests/tokenspeed_round/cost_records.py
new file mode 100644
index 0000000..d9df5f0
--- /dev/null
+++ b/tests/tokenspeed_round/cost_records.py
@@ -0,0 +1,68 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Host-only structural records for packing tests, with no policy implementation."""
+
+from dataclasses import dataclass, replace
+
+
+@dataclass(frozen=True)
+class IntervalCosts:
+ verify_widths: tuple[int, ...]
+ verify_cost_deltas: tuple[tuple[float, ...], ...]
+ draft_cost: float
+ model_cost_ratio: float
+ depth_thresholds: tuple[tuple[float, ...], ...]
+ verify_tier: int
+ verify_thresholds: tuple[float, float]
+
+
+@dataclass(frozen=True)
+class BatchCosts:
+ cost_batch_size: int
+ cache_length_step: int
+ intervals: tuple[IntervalCosts, ...]
+
+
+@dataclass(frozen=True)
+class PolicyCosts:
+ batches: tuple[BatchCosts, ...]
+ history_floors: tuple[int, ...]
+ initial_widths: tuple[int, ...]
+ async_layer_ratio: float
+
+
+def records() -> PolicyCosts:
+ first = IntervalCosts(
+ verify_widths=(0, 3),
+ # A value below the producer's usual cutoff must be packed unchanged.
+ verify_cost_deltas=((0.0, 0.01234567890123456), (0.0, 0.0)),
+ draft_cost=1.2345678901234567,
+ model_cost_ratio=11.123456789012345,
+ depth_thresholds=tuple((0.125 + tier, 0.75 + tier) for tier in range(5)),
+ verify_tier=0,
+ verify_thresholds=(0.9123456789012345, 1.1234567890123456),
+ )
+ second = replace(
+ first,
+ verify_widths=(0, 1, 7),
+ verify_cost_deltas=((0.0, 0.5, 0.75), (0.0, 0.0, 0.25), (0.0, 0.0, 0.0)),
+ )
+ # First-use IDs are 7 then 2; repeated measurements have distinct live decisions.
+ batches = tuple(
+ (
+ BatchCosts(
+ 7,
+ 512,
+ (
+ replace(
+ first, verify_tier=i % 4, verify_thresholds=(0.5 + i, 0.75 + i)
+ ),
+ ),
+ )
+ if i % 2 == 0
+ else BatchCosts(2, 1024, (second, first))
+ )
+ for i in range(32)
+ )
+ return PolicyCosts(batches, (16, 8, 4, 2, 32), (2, 2, 2, 2), 0.73)
diff --git a/tests/tokenspeed_round/test_chain_policy_cost.py b/tests/tokenspeed_round/test_chain_policy_cost.py
new file mode 100644
index 0000000..01c2657
--- /dev/null
+++ b/tests/tokenspeed_round/test_chain_policy_cost.py
@@ -0,0 +1,175 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""CPU packing and startup rejection for structural chain policy records."""
+
+from dataclasses import astuple, replace
+
+import pytest
+import torch
+
+from eagle_harness.tokenspeed.tree_round.device_policy import DevicePolicy
+from eagle_harness.tokenspeed.tree_round.policy_cost import (
+ build_chain_tables,
+)
+from tests.tokenspeed_round.chain_cost_records import records
+
+
+def pack(costs, *, depth=7, verify=8, widths=()):
+ return build_chain_tables(
+ costs,
+ tree_depth=depth,
+ verify_num=verify,
+ chain_width_table=widths,
+ device=torch.device("cpu"),
+ )
+
+
+def test_pack_each_live_batch_exactly_and_zero_padding():
+ costs = records()
+ tables = pack(costs)
+ assert tables.chain_f64.shape == (512, 2, 2, 7, 5)
+ assert tables.chain_f64.dtype == torch.float64
+ assert tables.batch_table.dtype == torch.int64
+ for i, batch in enumerate(costs.batches):
+ assert tables.batch_table[i].tolist() == [
+ i,
+ 0,
+ len(batch.intervals),
+ batch.cache_length_step,
+ 0,
+ ]
+ for j, interval in enumerate(batch.intervals):
+ expected = [list(astuple(terms)) for terms in interval]
+ assert tables.chain_f64[i, j, 0].tolist() == expected
+ assert tables.chain_f64[i, j, 1].tolist() == expected
+ assert torch.count_nonzero(tables.chain_f64[i, len(batch.intervals) :]) == 0
+ for unused in (
+ tables.interval_i32,
+ tables.interval_f64,
+ tables.tier_table,
+ tables.verify_i32,
+ tables.verify_f64,
+ ):
+ assert unused.numel() == 0
+
+
+def test_width_table_uses_greatest_covered_live_threshold():
+ tables = pack(records(), widths=((4, 8), (16, 4), (512, 2)))
+ widths = tables.batch_table[:, 4].tolist()
+ assert widths == [0] * 3 + [8] * 12 + [4] * 496 + [2]
+
+
+ "widths",
+ [
+ ((0, 2),),
+ ((4, 2), (4, 4)),
+ ((5, 2), (4, 4)),
+ ((1, 1),),
+ ((1, 9),),
+ ((True, 4),),
+ ((1, 2.0),),
+ ((1, 2, 3),),
+ ],
+)
+def test_invalid_width_table_rejected(widths):
+ with pytest.raises(ValueError, match="width table"):
+ pack(records(), widths=widths)
+
+
[email protected]("depth,verify", [(1, 8), (16, 8), (7, 1), (7, 17)])
+def test_invalid_chain_shape_rejected(depth, verify):
+ with pytest.raises(ValueError):
+ pack(records(), depth=depth, verify=verify)
+
+
+ "change",
+ [{"cache_length_step": 0}, {"cache_length_step": 2**63}, {"intervals": ()}],
+)
+def test_invalid_chain_batch_rejected(change):
+ costs = records()
+ with pytest.raises(ValueError):
+ pack(
+ replace(
+ costs, batches=(replace(costs.batches[0], **change), *costs.batches[1:])
+ )
+ )
+
+
+def test_chain_batch_count_and_depth_must_match():
+ with pytest.raises(ValueError):
+ pack(replace(records(), batches=records().batches[:-1]))
+ with pytest.raises(ValueError):
+ pack(records(depth=5))
+
+
+ "depth,change",
+ [
+ (2, {"gain_scale": 0.0}),
+ (2, {"cost": -1.0}),
+ (2, {"threshold": float("nan")}),
+ (2, {"cliff_gain_scale": 0.0}),
+ (2, {"cliff_cost": 0.0}),
+ (2, {"cliff_cost": float("inf")}),
+ (1, {"gain_scale": 1.0}),
+ ],
+)
+def test_invalid_stop_terms_rejected(depth, change):
+ costs = records()
+ batch = costs.batches[0]
+ interval = list(batch.intervals[0])
+ interval[depth] = replace(interval[depth], **change)
+ batch = replace(batch, intervals=(tuple(interval), *batch.intervals[1:]))
+ with pytest.raises(ValueError):
+ pack(replace(costs, batches=(batch, *costs.batches[1:])))
+
+
+ "change",
+ [
+ {"node_top_k": 2},
+ {"tree_depth": 16},
+ {"verify_num": 17},
+ {"exec_mode": 1},
+ {"benchmark_config": "eval"},
+ {"chain_width_table": ((1, 9),)},
+ {"device": torch.device("cpu")},
+ ],
+)
+def test_invalid_chain_policy_rejected_before_cuda(change):
+ kwargs = {
+ "verify_num": 8,
+ "node_top_k": 1,
+ "tree_depth": 7,
+ "compute_intensity": "chain_intensity",
+ "is_moe_target": False,
+ "exec_mode": 0,
+ "benchmark_config": "",
+ "chain_width_table": (),
+ "device": torch.device("cuda"),
+ }
+ kwargs.update(change)
+ with pytest.raises(ValueError):
+ DevicePolicy(records(), **kwargs)
+
+
[email protected]("custom", [False, True])
+def test_core_exports_pack_without_recomputing_terms(custom):
+ from tests.tokenspeed_round.chain_core_costs import model
+
+ core = model(depth=7, verify=8, custom=custom)
+ costs = core.chain_policy_costs()
+ tables = pack(costs)
+ # Shared measured batch 4 must not merge the live-batch tier distinction.
+ assert (
+ tables.chain_f64[0, 0, 0, 2].tolist() != tables.chain_f64[2, 0, 0, 2].tolist()
+ )
+ for bs in (1, 2, 3, 4, 33, 512):
+ for interval_id, interval in enumerate(costs.batches[bs - 1].intervals):
+ for depth, terms in enumerate(interval):
+ assert tables.chain_f64[bs - 1, interval_id, 0, depth].tolist() == list(
+ astuple(terms)
+ )
diff --git a/tests/tokenspeed_round/test_chain_sampled_policy_gpu.py b/tests/tokenspeed_round/test_chain_sampled_policy_gpu.py
new file mode 100644
index 0000000..20af8b3
--- /dev/null
+++ b/tests/tokenspeed_round/test_chain_sampled_policy_gpu.py
@@ -0,0 +1,325 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Chain and sampled policy state across graph replays; no model weights needed."""
+
+import math
+from dataclasses import replace
+
+import pytest
+import torch
+
+pytest.importorskip("tvm_ffi", reason="TokenSpeed round kernels require apache-tvm-ffi")
+
+from eagle_harness.tokenspeed.tree_round.device_policy import DevicePolicy
+from tests.tokenspeed_round.chain_cost_records import records
+from tests.tokenspeed_round.cost_records import BatchCosts, IntervalCosts, PolicyCosts
+
+pytestmark = pytest.mark.skipif(
+ not torch.cuda.is_available(), reason="CUDA GPU is required"
+)
+
+
+def chain_policy(*, depth=7, verify=8, widths=(), costs=None):
+ return DevicePolicy(
+ records(depth) if costs is None else costs,
+ verify_num=verify,
+ node_top_k=1,
+ tree_depth=depth,
+ compute_intensity="chain_intensity",
+ is_moe_target=False,
+ exec_mode=0,
+ benchmark_config="",
+ chain_width_table=widths,
+ device=torch.device("cuda"),
+ )
+
+
+def capture_round(policy):
+ capacity = 512 if policy.chain else 32
+ live = torch.zeros(1, dtype=torch.int32, device="cuda")
+ # Exercise the existing strided frontier contract.
+ frontier = torch.zeros((capacity, 2), dtype=torch.int64, device="cuda")[:, 0]
+ sampled = torch.zeros(1, dtype=torch.bool, device="cuda")
+ deltas = torch.zeros(policy.node_top_k + 1, device="cuda")
+ scores = torch.zeros((capacity, policy.verify_num_limit), device="cuda")
+
+ def run_round():
+ policy.begin_round(live, frontier, sampled)
+ for depth in range(1, policy.tree_depth):
+ policy.decide(depth, deltas)
+ policy.select_verify(scores)
+
+ # Resolve the FFI launch paths before capture; idle warmups are not rounds.
+ run_round()
+ torch.cuda.synchronize()
+ stream = torch.cuda.Stream()
+ stream.wait_stream(torch.cuda.current_stream())
+ graph = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(graph, stream=stream):
+ run_round()
+ torch.cuda.current_stream().wait_stream(stream)
+ return graph, live, frontier, sampled, deltas, scores
+
+
+def replay(inputs, *, batch, gain, sample):
+ graph, live, frontier, sampled, deltas, _ = inputs
+ live.fill_(batch)
+ frontier.fill_(1024)
+ sampled.fill_(sample)
+ deltas.zero_()
+ deltas[1:].fill_(gain)
+ graph.replay()
+ torch.cuda.synchronize()
+
+
[email protected]("depth,verify", [(2, 2), (3, 4), (7, 8), (15, 16), (15, 4)])
+def test_chain_greedy_stop_and_full_round(depth, verify):
+ policy = chain_policy(depth=depth, verify=verify)
+ inputs = capture_round(policy)
+ for batch in (1, 2, 3, 33, 512):
+ policy.observe_batch_size(batch)
+ for gain in (0.0, 100000.0):
+ replay(inputs, batch=batch, gain=gain, sample=False)
+ last = min(2, depth - 1) if gain == 0 else depth - 1
+ assert policy.last_depth.item() == last
+ assert policy.cumu_count.item() == last + 2
+ assert policy.verify_num.item() == min(last + 2, verify)
+ assert policy.verify_count.item() == policy.verify_num.item()
+ assert policy.past_verify_num.item() == 16
+ assert policy.widths[1 : last + 1].tolist() == [1] * last
+ assert policy.cumu_starts[1 : last + 1].tolist() == list(range(2, last + 2))
+ assert policy.work_sizes[1 : last + 1].tolist() == [
+ d + 1 if d % 2 and d < depth - 1 else 0 for d in range(1, last + 1)
+ ]
+ assert policy.go[last + 1 :].count_nonzero().item() == 0
+ with pytest.raises(ValueError):
+ policy.observe_batch_size(513)
+
+
+def test_sampled_chain_updates_next_plan_without_using_current_proposals():
+ policy = chain_policy()
+ inputs = capture_round(policy)
+ # First sampled depth is 0. Low gain holds the next plan at 2; high gain
+ # grows it. Current low gain at depth 2 cannot shorten a planned depth 4.
+ script = [
+ (True, 0.0, 0),
+ (True, 0.0, 2),
+ (True, 100000.0, 2),
+ (True, 0.0, 4),
+ (False, 100000.0, 6),
+ (True, 100000.0, 2),
+ (True, 100000.0, 4),
+ (True, 100000.0, 6),
+ ]
+ for seq, (sampled, gain, last) in enumerate(script, start=1):
+ replay(inputs, batch=512, gain=gain, sample=sampled)
+ assert policy.last_depth.item() == last
+ assert policy.cumu_count.item() == last + 2
+ assert policy.verify_num.item() == last + 2
+ assert policy.go_ready(last + 1, seq) is False
+ replay(inputs, batch=0, gain=0.0, sample=True)
+ assert policy.cumu_count.item() == 0
+ replay(inputs, batch=33, gain=0.0, sample=True)
+ assert policy.last_depth.item() == 6
+
+
+def test_chain_width_table_overrides_sampled_and_greedy_without_changing_plan():
+ policy = chain_policy(widths=((2, 2), (8, 3), (32, 8)))
+ inputs = capture_round(policy)
+ replay(inputs, batch=1, gain=0.0, sample=True)
+ assert policy.last_depth.item() == 0 # next uncovered plan is 2
+ for seq, (batch, width, sample) in enumerate(
+ [
+ (2, 2, True),
+ (7, 2, False),
+ (8, 3, True),
+ (31, 3, False),
+ (32, 8, True),
+ (512, 8, False),
+ ],
+ start=2,
+ ):
+ replay(inputs, batch=batch, gain=0.0, sample=sample)
+ assert policy.verify_num.item() == width
+ assert policy.cumu_count.item() == width
+ assert policy.last_depth.item() == width - 2
+ assert policy.work_sizes.count_nonzero().item() == 0
+ assert policy.go_ready(width - 1, seq) is False
+ assert policy.go[1:].tolist() == [int(d <= width - 2) for d in range(1, 8)]
+ replay(inputs, batch=1, gain=0.0, sample=True)
+ assert policy.last_depth.item() == 2
+
+
+def tree_policy(async_layer_ratio):
+ interval = IntervalCosts(
+ verify_widths=(0, 1, 5),
+ verify_cost_deltas=((0.0, 0.1, 0.6), (0.0, 0.0, 0.5), (0.0, 0.0, 0.0)),
+ draft_cost=1.0,
+ model_cost_ratio=10.0,
+ depth_thresholds=((1.0,) * 7,) * 5,
+ verify_tier=0,
+ verify_thresholds=(2.0, 2.0),
+ )
+ costs = PolicyCosts(
+ (BatchCosts(4, 1024, (interval,)),) * 32,
+ (16, 8, 4, 2, 32),
+ (2, 2, 2, 2),
+ async_layer_ratio,
+ )
+ return DevicePolicy(
+ costs,
+ verify_num=8,
+ node_top_k=2,
+ tree_depth=7,
+ compute_intensity="high_intensity",
+ is_moe_target=False,
+ exec_mode=0,
+ benchmark_config="",
+ chain_width_table=(),
+ device=torch.device("cuda"),
+ )
+
+
[email protected]("first_score,lagged_width", [(0.0, 2), (1.0, 6)])
+def test_sampled_tree_first_verify_is_unranked_then_uses_previous_scores(
+ first_score, lagged_width
+):
+ policy = tree_policy(0.73)
+ inputs = capture_round(policy)
+ inputs[-1].fill_(first_score)
+ replay(inputs, batch=4, gain=0.0, sample=True)
+ assert policy.last_depth.item() == 6
+ assert policy.verify_num.item() == 6
+ inputs[-1].fill_(1.0 - first_score)
+ replay(inputs, batch=4, gain=100.0, sample=True)
+ assert policy.last_depth.item() == 1 # prior round's earliest cost stop
+ assert policy.verify_num.item() == lagged_width
+ replay(inputs, batch=4, gain=0.0, sample=True)
+ assert policy.last_depth.item() == 3 # previous high gain grew the plan
+ replay(inputs, batch=4, gain=100.0, sample=True)
+ assert policy.last_depth.item() == 1
+
+
[email protected]("ratio,last", [(0.73, 1), (0.9, 6)])
+def test_tree_retains_custom_async_ratio(ratio, last):
+ policy = tree_policy(ratio)
+ replay(capture_round(policy), batch=4, gain=0.13, sample=False)
+ assert policy.last_depth.item() == last
+
+
[email protected]("custom", [False, True])
+def test_chain_rounds_match_core_cost_model(custom):
+ from tests.tokenspeed_round.chain_core_costs import model
+
+ core = model(custom=custom)
+ policy = chain_policy(depth=15, verify=16, costs=core.chain_policy_costs())
+ graph, live, frontier, _sampled, deltas, _ = capture_round(policy)
+ generator = torch.Generator().manual_seed(920)
+ for bs in (1, 2, 3, 4, 33, 512):
+ live.fill_(bs)
+ for context in (0, 2047, 2048, 8192):
+ frontier.fill_(context)
+ core.update_interval(bs, context)
+ for gain in [0.0, 10.0, *torch.rand(16, generator=generator).tolist()]:
+ # These are the actual float32 inputs the device widens.
+ host_deltas = torch.tensor(
+ [0.1, 0.1 + gain], dtype=torch.float32
+ ).tolist()
+ deltas.copy_(torch.tensor(host_deltas))
+ last = next(
+ (
+ d
+ for d in range(1, 15)
+ if d == 14 or core.chain_stop(d, bs, host_deltas)
+ ),
+ 14,
+ )
+ graph.replay()
+ torch.cuda.synchronize()
+ assert policy.last_depth.item() == last
+ assert policy.verify_num.item() == last + 2
+
+
[email protected]("above_boundary", [False, True])
+def test_chain_gain_division_preserves_rounding_order(above_boundary):
+ costs = records(depth=4)
+ delta_values = torch.tensor([0.163, 0.3], dtype=torch.float32).tolist()
+ raw_gain = delta_values[1] - delta_values[0]
+ denominator = 1.6454386831000494
+ threshold = raw_gain * 2.0 / denominator
+ # This input distinguishes division from multiplying a precomputed reciprocal.
+ assert raw_gain * (2.0 / denominator) < threshold
+ if above_boundary:
+ threshold = math.nextafter(threshold, math.inf)
+ batch = costs.batches[0]
+ intervals = []
+ for interval in batch.intervals:
+ terms = replace(
+ interval[2],
+ gain_scale=denominator,
+ cost=1.0,
+ threshold=threshold,
+ cliff_gain_scale=0.0,
+ cliff_cost=0.0,
+ )
+ intervals.append((*interval[:2], terms, interval[3]))
+ costs = replace(
+ costs, batches=(replace(batch, intervals=tuple(intervals)), *costs.batches[1:])
+ )
+ policy = chain_policy(depth=4, verify=5, costs=costs)
+ graph, live, _frontier, _sampled, deltas, _ = capture_round(policy)
+ live.fill_(1)
+ deltas.copy_(torch.tensor(delta_values))
+ graph.replay()
+ torch.cuda.synchronize()
+ assert policy.last_depth.item() == (2 if above_boundary else 3)
+
+
[email protected]("cliff", [False, True])
+def test_chain_cliff_can_rescue_a_stopping_decision(cliff):
+ costs = records(depth=4)
+ batch = costs.batches[0]
+ interval = batch.intervals[0]
+ terms = replace(
+ interval[2],
+ gain_scale=2.0,
+ cost=1.0,
+ threshold=0.2,
+ cliff_gain_scale=1.0 if cliff else 0.0,
+ cliff_cost=1.0 if cliff else 0.0,
+ )
+ interval = (*interval[:2], terms, interval[3])
+ costs = replace(
+ costs, batches=(replace(batch, intervals=(interval,)), *costs.batches[1:])
+ )
+ policy = chain_policy(depth=4, verify=5, costs=costs)
+ replay(capture_round(policy), batch=1, gain=0.125, sample=False)
+ assert policy.last_depth.item() == (3 if cliff else 2)
+
+
+def test_chain_boundary_rejects_wrong_frontier_and_delta_shapes():
+ policy = chain_policy()
+ live = torch.ones(1, dtype=torch.int32, device="cuda")
+ sampled = torch.zeros(1, dtype=torch.bool, device="cuda")
+ with pytest.raises(Exception, match="frontier.ndim"):
+ policy.begin_round(
+ live, torch.zeros((1, 1), dtype=torch.int64, device="cuda"), sampled
+ )
+ with pytest.raises(Exception, match="work deltas"):
+ policy.decide(2, torch.zeros(3, device="cuda"))
+
+
[email protected]("rows,cols,capacity", [(33, 2, 128), (2, 65, 128), (2, 2, 1)])
+def test_ranked_score_capacity_checks_remain_effective(rows, cols, capacity):
+ from eagle_harness.tokenspeed.tree_round.ops.policy import (
+ eagle_harness_ranked_scores,
+ )
+
+ top = torch.zeros((33, 65), device="cuda")
+ scalars = torch.tensor([rows, cols, 0, 0], dtype=torch.int32, device="cuda")
+ r, c, flat, count = scalars.split(1)
+ out = torch.full((capacity,), 123.0, device="cuda")
+ eagle_harness_ranked_scores(top, r, c, flat, out, count)
+ assert count.item() == -1
+ assert torch.all(out == 123.0).item()
diff --git a/tests/tokenspeed_round/test_core_costs.py b/tests/tokenspeed_round/test_core_costs.py
new file mode 100644
index 0000000..01e4058
--- /dev/null
+++ b/tests/tokenspeed_round/test_core_costs.py
@@ -0,0 +1,86 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""CPU integration: packed records retain the shared core's policy decisions."""
+
+import pytest
+import torch
+
+pytest.importorskip("eagle_harness")
+
+from eagle_harness.core.cost_model import CostModel, CostModelParams, SizeClass
+from eagle_harness.core.limits import ComputeIntensity
+from eagle_harness.tokenspeed.tree_round.policy_cost import build_tables
+from tests.tokenspeed_round.core_costs import cost_fixture, policy_costs
+
+
+def pack(costs, k, depth, moe, intensity):
+ return build_tables(
+ policy_costs(costs, k=k, depth=depth, verify=32, moe=moe, intensity=intensity),
+ device=torch.device("cpu"),
+ )
+
+
[email protected]("intensity", ["high_intensity", "low_intensity"])
[email protected]("moe", [False, True])
[email protected]("k", [2, 4, 8])
+def test_table_decisions_match_core(k, moe, intensity):
+ costs = cost_fixture()
+ depth = 8
+ packed = pack(costs, k, depth, moe, intensity)
+ params = CostModelParams(depth_loss_ratio=0.08 if moe else 0.04)
+ model = CostModel(costs, params, ComputeIntensity(intensity), k, depth, 32, moe)
+ assert packed.tier_table.tolist() == [16, 8, 4, 2, 32, k, k, min(k, 4), min(k, 4)]
+
+ for bs in (1, 2, 3, 4, 6, 8, 20, 32):
+ cost_id = packed.batch_table[bs - 1, 0].item()
+ table = model.table(bs)
+ for interval in range(2):
+ context = (interval + 1) * table.cache_length_step
+ verify = model.verify_cost(bs, context)
+ assert packed.verify_i32[bs - 1, interval].item() == int(model.tier.size)
+ assert packed.verify_f64[bs - 1, interval].tolist() == [
+ verify.threshold * 0.95,
+ verify.threshold * 1.05,
+ ]
+ data = packed.interval_f64[cost_id, interval]
+ index = table.intervals[interval].target.index
+ assert packed.interval_i32[cost_id, interval].tolist() == [
+ len(index),
+ *index,
+ ]
+ for variant in range(5):
+ model.tier.size = SizeClass(variant % 4)
+ model.tier.tiny = variant == 4
+ row = model.draft_cost_row(bs, context)
+ assert data[:2].tolist() == [row.cost_state, row.model_cost_ratio]
+ width = packed.tier_table[5 + int(model.tier.size)].item()
+ for d in (3, 5):
+ threshold = data[2 + variant * depth + d].item()
+ boundary_gain = (
+ threshold
+ / params.async_layer_ratio
+ / row.model_cost_ratio
+ * row.cost_state
+ )
+ for factor in (0.9, 1.1):
+ deltas = [1.0] + [1.0 + boundary_gain * factor] * k
+ model.tier.tiny = variant == 4
+ decision = model.tree_width(d, bs, 32, row, deltas)
+ gain = (
+ (deltas[width] - deltas[0])
+ / data[0].item()
+ * data[1].item()
+ * 0.9
+ )
+ assert (gain < threshold) == decision.stop
+ delta = data[2 + 5 * depth :].view(len(index), len(index))
+ values = table.intervals[interval].target.ratio
+ for a in range(len(index)):
+ for b in range(len(index)):
+ expected = (
+ values[b] - values[a]
+ if b > a and values[b] - values[a] > 0.04
+ else 0.0
+ )
+ assert delta[a, b].item() == expected
diff --git a/tests/tokenspeed_round/test_device_chain.py b/tests/tokenspeed_round/test_device_chain.py
new file mode 100644
index 0000000..dfa8a39
--- /dev/null
+++ b/tests/tokenspeed_round/test_device_chain.py
@@ -0,0 +1,73 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Graph-handle ownership on CPU, with graph uploads replaced by a test driver."""
+
+import contextlib
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+from eagle_harness.tokenspeed.tree_round import chain as module
+
+
+def chain_driver(monkeypatch):
+ chain = object.__new__(module.DeviceChain)
+ chain.device = torch.device("cpu")
+ chain.last_depth = 3
+ chain._execs = torch.zeros((5, 6), dtype=torch.int64)
+ chain._handles = {}
+ destroyed = []
+ monkeypatch.setattr(torch.cuda, "device", lambda *_: contextlib.nullcontext())
+ monkeypatch.setattr(torch.cuda, "stream", lambda *_: contextlib.nullcontext())
+ monkeypatch.setattr(torch.cuda, "synchronize", lambda *_: None)
+ monkeypatch.setattr(module, "eagle_harness_chain_destroy", destroyed.append)
+ stream = SimpleNamespace(
+ device=torch.device("cpu"), cuda_stream=123, synchronize=lambda: None
+ )
+ depths = [
+ SimpleNamespace(raw_cuda_graph=lambda: 10),
+ SimpleNamespace(raw_cuda_graph=lambda: 20),
+ ]
+ finalize = [SimpleNamespace(raw_cuda_graph=lambda: 30)]
+ return chain, stream, depths, finalize, destroyed
+
+
+def test_chain_publishes_and_releases_owned_handles(monkeypatch):
+ chain, stream, depths, finalize, destroyed = chain_driver(monkeypatch)
+ monkeypatch.setattr(
+ module, "eagle_harness_chain_instantiate", lambda graph, stream: graph + 1
+ )
+ chain.instantiate(4, depths, finalize, stream)
+ assert chain._execs[4].tolist() == [0, 0, 11, 21, 31, 0]
+ with pytest.raises(ValueError, match="already instantiated"):
+ chain.instantiate(4, depths, finalize, stream)
+ chain.release()
+ chain.release()
+ assert destroyed == [11, 21, 31]
+ assert not chain._execs.any()
+
+
+def test_partial_upload_failure_destroys_handles_without_publishing(monkeypatch):
+ chain, stream, depths, finalize, destroyed = chain_driver(monkeypatch)
+
+ def upload(graph, stream):
+ if graph == 20:
+ raise RuntimeError("upload failed")
+ return graph + 1
+
+ monkeypatch.setattr(module, "eagle_harness_chain_instantiate", upload)
+ with pytest.raises(RuntimeError, match="upload failed"):
+ chain.instantiate(4, depths, finalize, stream)
+ assert destroyed == [11]
+ assert not chain._handles
+ assert not chain._execs.any()
+
+
+def test_chain_refuses_invalid_capture_counts(monkeypatch):
+ chain, stream, depths, finalize, destroyed = chain_driver(monkeypatch)
+ for ds, fs in ((depths * 2, finalize), (depths, finalize * 3), (depths, [])):
+ with pytest.raises(ValueError, match="depth prefix"):
+ chain.instantiate(4, ds, fs, stream)
+ assert not destroyed
diff --git a/tests/tokenspeed_round/test_device_chain_gpu.py b/tests/tokenspeed_round/test_device_chain_gpu.py
new file mode 100644
index 0000000..132a2c7
--- /dev/null
+++ b/tests/tokenspeed_round/test_device_chain_gpu.py
@@ -0,0 +1,97 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""EAGLE-Harness device-chained rounds: from an ordinary first graph, graphs
+captured by torch and instantiated for device launch run the depths the go
+flags select and then the greedy finalize, and the
+launching stream orders its later work after the whole chain."""
+
+import sys
+
+import pytest
+import torch
+
+pytest.importorskip("tvm_ffi", reason="TokenSpeed round kernels require apache-tvm-ffi")
+
+from eagle_harness.tokenspeed.tree_round.chain import DeviceChain
+
+pytestmark = pytest.mark.skipif(
+ not torch.cuda.is_available(), reason="CUDA GPU is required"
+)
+
+_LAST_DEPTH = 4
+_FINALIZE = 100
+
+
[email protected]("rows", [4, 33, 512])
[email protected]("captured_depth", [2, _LAST_DEPTH])
[email protected]("sampled_finalize", [False, True])
+def test_chain_follows_the_go_flags_to_the_selected_finalize(
+ rows, captured_depth, sampled_finalize
+) -> None:
+ device = torch.device("cuda")
+ log = torch.zeros(64, dtype=torch.int64, device=device)
+ count = torch.zeros(1, dtype=torch.int64, device=device)
+ go = torch.zeros(_LAST_DEPTH + 1, dtype=torch.int32, device=device)
+ sampled = torch.zeros(1, dtype=torch.bool, device=device)
+ chain = DeviceChain(rows, _LAST_DEPTH, device)
+ side = torch.cuda.Stream()
+
+ def note(tag: int) -> None:
+ log.index_fill_(0, count, tag)
+ count.add_(1)
+
+ stream = torch.cuda.Stream()
+ graphs = []
+ with torch.cuda.stream(stream):
+ for depth in range(1, captured_depth + 1):
+ # Depth 1 is an ordinary graph; the rest launch on the device.
+ graph = torch.cuda.CUDAGraph(keep_graph=depth > 1)
+ with torch.cuda.graph(graph, stream=stream):
+ # The launch is enqueued on a side branch, as after a depth's decision.
+ side.wait_stream(stream)
+ with torch.cuda.stream(side):
+ chain.end_depth(rows, depth, go, sampled)
+ torch.cuda._sleep(100_000)
+ note(depth)
+ stream.wait_stream(side)
+ graphs.append(graph)
+ for finalize in (
+ (_FINALIZE, _FINALIZE + 1) if sampled_finalize else (_FINALIZE,)
+ ):
+ graph = torch.cuda.CUDAGraph(keep_graph=True)
+ with torch.cuda.graph(graph, stream=stream):
+ note(finalize)
+ graphs.append(graph)
+ chain.instantiate(rows, graphs[1:captured_depth], graphs[captured_depth:], stream)
+ # Uploaded on the capture stream; the rounds launch from the default one.
+ stream.synchronize()
+
+ def run(go_flags: list[int], draw: bool) -> list[int]:
+ go.copy_(torch.tensor([0, *go_flags], dtype=torch.int32))
+ sampled.fill_(draw)
+ count.zero_()
+ graphs[0].replay()
+ # Ordered after the whole chain.
+ note(-1)
+ torch.cuda.synchronize()
+ return log[: int(count)].tolist()
+
+ # go[d + 1] is read once depth d's graph ends; the last depth always finalizes.
+ assert run([int(d <= captured_depth) for d in range(1, 5)], False) == [
+ *range(1, captured_depth + 1),
+ _FINALIZE,
+ -1,
+ ]
+ assert run([1, 0, 1, 1], False) == [1, _FINALIZE, -1]
+ assert run([1, 1, 0, 1], False) == [1, 2, _FINALIZE, -1]
+ if sampled_finalize:
+ assert run([1, 0, 0, 0], True) == [1, _FINALIZE + 1, -1]
+ assert run([1, 1, 0, 0], True) == [1, 2, _FINALIZE + 1, -1]
+ torch.cuda.synchronize()
+ chain.release()
+ chain.release() # Releasing twice owns no handles the second time.
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, *sys.argv[1:]]))
diff --git a/tests/tokenspeed_round/test_device_policy_gpu.py b/tests/tokenspeed_round/test_device_policy_gpu.py
new file mode 100644
index 0000000..fdf416d
--- /dev/null
+++ b/tests/tokenspeed_round/test_device_policy_gpu.py
@@ -0,0 +1,164 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Graph-replayed greedy policy decisions against core CostModel."""
+
+import sys
+
+import pytest
+import torch
+
+pytest.importorskip("tvm_ffi", reason="TokenSpeed round kernels require apache-tvm-ffi")
+
+pytest.importorskip("eagle_harness")
+
+from eagle_harness.core.cost_model import CostModel, CostModelParams
+from eagle_harness.core.limits import ComputeIntensity
+from eagle_harness.tokenspeed.tree_round.device_policy import DevicePolicy
+from tests.tokenspeed_round.core_costs import cost_fixture, policy_costs
+
+pytestmark = pytest.mark.skipif(
+ not torch.cuda.is_available(), reason="CUDA GPU is required"
+)
+
+
[email protected]("async_layer_ratio", [0.9, 0.73])
[email protected]("k", [2, 4, 8])
[email protected]("moe", [False, True])
+def test_captured_policy_rounds_match_core(k, moe, async_layer_ratio):
+ device, depth, verify = torch.device("cuda"), 8, 32
+ costs = cost_fixture()
+ policy = DevicePolicy(
+ policy_costs(
+ costs,
+ k=k,
+ depth=depth,
+ verify=verify,
+ moe=moe,
+ async_layer_ratio=async_layer_ratio,
+ ),
+ verify_num=verify,
+ node_top_k=k,
+ tree_depth=depth,
+ compute_intensity="high_intensity",
+ is_moe_target=moe,
+ exec_mode=0,
+ benchmark_config="",
+ chain_width_table=(),
+ device=device,
+ )
+ model = CostModel(
+ costs,
+ CostModelParams(
+ depth_loss_ratio=0.08 if moe else 0.04, async_layer_ratio=async_layer_ratio
+ ),
+ ComputeIntensity.HIGH,
+ k,
+ depth,
+ verify,
+ moe,
+ )
+ live = torch.zeros(1, dtype=torch.int32, device=device)
+ frontier = torch.zeros(32, dtype=torch.int64, device=device)
+ sampled = torch.zeros(1, dtype=torch.bool, device=device)
+ deltas = torch.zeros(k + 1, device=device)
+ scores = torch.zeros((32, verify), device=device)
+ # Load/warm launch paths with no live round before capture.
+ policy.begin_round(live, frontier, sampled)
+ for d in range(1, depth):
+ policy.decide(d, deltas)
+ policy.select_verify(scores)
+ torch.cuda.synchronize()
+ stream = torch.cuda.Stream()
+ stream.wait_stream(torch.cuda.current_stream())
+ graph = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(graph, stream=stream):
+ policy.begin_round(live, frontier, sampled)
+ for d in range(1, depth):
+ policy.decide(d, deltas)
+ policy.select_verify(scores)
+ torch.cuda.current_stream().wait_stream(stream)
+
+ previous = None
+ generator = torch.Generator().manual_seed(1709 + k)
+ for round_id, (bs, gain) in enumerate(
+ [(1, 0.02), (32, 0.5), (4, 0.001), (1, 0.9)] * 5, 2
+ ):
+ context = 1024 if round_id % 2 else 2300
+ policy.observe_batch_size(bs)
+ live.fill_(bs)
+ frontier.fill_(context)
+ delta_values = torch.linspace(1.0, 1.0 + gain, k + 1).tolist()
+ deltas.copy_(torch.tensor(delta_values))
+ top = (
+ torch.rand((bs, verify), generator=generator)
+ .sort(dim=-1, descending=True)
+ .values
+ )
+ top[:, 0] = 1.0
+ scores[:bs].copy_(top)
+ past = model.history_verify_num(bs)
+ row = model.draft_cost_row(bs, context)
+ width = model.tree_width(0, bs, past, row).width
+ start, expected_widths = 1 + k, []
+ for d in range(1, depth):
+ expected_widths.append(width)
+ decision = model.tree_width(d, bs, past, row, delta_values)
+ start += k * width
+ if decision.stop:
+ break
+ width = decision.width
+ count = model.verify_count(bs, start)
+ graph.replay()
+ torch.cuda.synchronize()
+ assert policy.past_verify_num.item() == past
+ assert policy.cumu_count.item() == start
+ assert policy.last_depth.item() == d
+ assert policy.widths[1 : d + 1].tolist() == expected_widths
+ assert policy.verify_count.item() == count
+ assert policy.go[d + 1].item() == 0
+ own = scores[:bs, :count].contiguous()
+ ranked = torch.cumsum(
+ own.view(-1) if model.tier.tiny else own.mean(dim=0), dim=0
+ ).tolist()
+ wanted, stop = model.verify_num_paged(
+ previous if previous is not None else ranked,
+ count,
+ bs,
+ context,
+ lagged=previous is not None,
+ )
+ assert not stop
+ assert policy.verify_num.item() == wanted
+ model.record_verify_num(bs, wanted)
+ previous = ranked
+
+
+def test_tiny_two_depth_round_always_finalizes():
+ policy = DevicePolicy(
+ policy_costs(cost_fixture(), k=2, depth=2, verify=8, moe=False),
+ verify_num=8,
+ node_top_k=2,
+ tree_depth=2,
+ compute_intensity="high_intensity",
+ is_moe_target=False,
+ exec_mode=0,
+ benchmark_config="",
+ chain_width_table=(),
+ device=torch.device("cuda"),
+ )
+ live = torch.ones(1, dtype=torch.int32, device="cuda")
+ frontier = torch.zeros(1, dtype=torch.int64, device="cuda")
+ sampled = torch.zeros(1, dtype=torch.bool, device="cuda")
+ deltas = torch.zeros(3, device="cuda")
+ # Simulate the persistent tiny tier reached after an earlier compared decision.
+ policy._state[0] = 1
+ policy.begin_round(live, frontier, sampled)
+ policy.decide(1, deltas)
+ assert policy.go[2].item() == 0
+ assert policy.cumu_count.item() == 7
+ assert policy.verify_count.item() == 7
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, *sys.argv[1:]]))
diff --git a/tests/tokenspeed_round/test_dynamic_gpu.py b/tests/tokenspeed_round/test_dynamic_gpu.py
new file mode 100644
index 0000000..d554dd8
--- /dev/null
+++ b/tests/tokenspeed_round/test_dynamic_gpu.py
@@ -0,0 +1,361 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Real dynamic-tree kernels: eager depths and GPU-tail-launched rounds agree."""
+
+from __future__ import annotations
+
+import contextlib
+import sys
+from dataclasses import replace
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+pytest.importorskip("tvm_ffi", reason="TokenSpeed round kernels require apache-tvm-ffi")
+
+# Keep the CPU suites independent of TokenSpeed's GPU-only package imports.
+if not torch.cuda.is_available():
+ pytest.skip("needs CUDA", allow_module_level=True)
+
+pytest.importorskip("tokenspeed", reason="requires the optional TokenSpeed engine")
+
+from tokenspeed.runtime.layers.attention.backends.paged.tree_verify import (
+ TreeDraftInputs,
+)
+
+pytest.importorskip("eagle_harness")
+
+from eagle_harness.core.config import HarnessConfig, Mode
+from eagle_harness.core.cost_table import BatchCostTable, CostCurve, IntervalCost
+from eagle_harness.tokenspeed.tree_round import dynamic as drafter_module
+from eagle_harness.tokenspeed.tree_round.device_policy import DevicePolicy
+from eagle_harness.tokenspeed.tree_round.dynamic import DynamicDrafter
+from tests.tokenspeed_round.core_costs import policy_costs
+
+
+class EagleHarness(DynamicDrafter):
+ @property
+ def dynamic(self):
+ return True
+
+
+BS, NODES, WINDOW, VERIFY_COUNT = 2, 9, 16, 4
+TREE_K, TREE_DEPTH, HIDDEN = 2, 6, 8
+
+
+class _OneDepthPolicy:
+ """Drafts depth 1 only and verifies two of its ranked nodes."""
+
+ tree_depth = 2
+ chain = False
+
+ def __init__(self) -> None:
+ int32 = {"dtype": torch.int32, "device": "cuda"}
+ self.cumu_count = torch.tensor([NODES], **int32)
+ self.verify_count = torch.tensor([VERIFY_COUNT], **int32)
+ self.verify_num = torch.tensor([2], **int32)
+
+ def observe_batch_size(self, batch_size: int) -> None:
+ pass
+
+ def deltas_depth(self, depth: int) -> bool:
+ return False
+
+ def decide(self, depth: int, work_deltas: torch.Tensor) -> None:
+ pass
+
+ def go_ready(self, depth: int, round_seq: int) -> bool:
+ return depth < self.tree_depth
+
+ def select_verify(self, top_scores: torch.Tensor) -> None:
+ pass
+
+
+def _drafter() -> EagleHarness:
+ drafter = EagleHarness.__new__(EagleHarness)
+ drafter.policy = _OneDepthPolicy()
+ drafter.config = HarnessConfig(mode=Mode.SERVE, data_path="/unused")
+ drafter.spec_num_steps = TREE_DEPTH
+ drafter.spec_num_tokens = WINDOW
+ drafter.input_buffers = SimpleNamespace(all_extends_mid_chunk=False)
+ # Every node a child of the root: any ranking is a valid tree.
+ prev = torch.zeros((BS, NODES), dtype=torch.int64, device="cuda")
+ prev[:, 0] = -1
+ gen = torch.Generator(device="cuda").manual_seed(71)
+ scores = torch.rand((BS, NODES), device="cuda", generator=gen)
+ scores[:, 0] = 2.0
+ drafter._pool = {
+ "scores": scores,
+ "tokens": torch.arange(BS * NODES, device="cuda").view(BS, NODES),
+ "prev": prev,
+ }
+ drafter._round = {
+ "root_tokens": torch.zeros(BS, dtype=torch.int32, device="cuda"),
+ "rows": torch.arange(BS, device="cuda"),
+ "frontier": torch.zeros(BS, dtype=torch.int64, device="cuda"),
+ "live_rows": torch.zeros(1, dtype=torch.int32, device="cuda"),
+ "sampled": torch.zeros(1, dtype=torch.bool, device="cuda"),
+ "work_deltas": torch.zeros((2, VERIFY_COUNT + 1), device="cuda"),
+ "top_scores": torch.zeros((BS, WINDOW), device="cuda"),
+ "top_index": torch.zeros((BS, WINDOW), dtype=torch.int64, device="cuda"),
+ }
+ drafter.runtime_states = SimpleNamespace(
+ future_input_map=torch.zeros((BS, WINDOW), dtype=torch.int32, device="cuda"),
+ future_parent_map=torch.zeros((BS, WINDOW), dtype=torch.int32, device="cuda"),
+ )
+ drafter._live_rows = 0
+ drafter._live_sampled = False
+ drafter._round_sampled = False
+ drafter._sampled_q = None
+ drafter._round_seq = 0
+ drafter._depth_done = [torch.cuda.Event() for _ in range(2)]
+ drafter._decide_stream = torch.cuda.Stream()
+ drafter._round_stream = torch.cuda.Stream()
+ drafter._chain = None
+ drafter._target_done = torch.cuda.Event()
+ drafter._round_done = torch.cuda.Event()
+ drafter._launched_rows = None
+ drafter._pending = None
+ # The depth's forward and pool update: nothing the stream ordering reads.
+ drafter._lane_context = lambda *args: None
+ drafter._draft_depth = lambda *args, **kwargs: None
+ drafter.attn_backend = SimpleNamespace(
+ override_num_extends=lambda n: contextlib.nullcontext()
+ )
+ return drafter
+
+
[email protected]("mode", [Mode.STATIC, Mode.SERVE])
+def test_missing_tree_is_rejected_before_first_forward(mode):
+ from eagle_harness.tokenspeed.drafter import HarnessDrafter
+
+ drafter = HarnessDrafter.__new__(HarnessDrafter)
+ drafter.config = HarnessConfig(mode=mode, data_path="/unused")
+ drafter.tree = None
+ drafter.tree_lanes = None
+ with pytest.raises(NotImplementedError, match="binds explicit draft ancestry"):
+ drafter.run(None, None, None, None)
+
+
+def test_dynamic_binding_has_no_native_sorter_depth_limit():
+ drafter = _drafter()
+ drafter.input_buffers.max_bs = BS
+ drafter.draft_reads_token_history = False
+ drafter.device = torch.device("cuda")
+ drafter.draft_model_runner = SimpleNamespace(
+ model=SimpleNamespace(
+ logits_processor=SimpleNamespace(
+ do_argmax=True, config=SimpleNamespace(vocab_size=128)
+ )
+ )
+ )
+ drafter._allocate = lambda *args: None
+ bound = []
+ drafter.attn_backend.bind_tree_draft = bound.append
+ spec = SimpleNamespace(config=SimpleNamespace(topk=4, num_steps=12, num_nodes=16))
+ drafter.bind_dynamic_tree(spec, _OneDepthPolicy())
+ assert drafter.tree_spec is spec
+ assert bound == [drafter.tree_lanes]
+ assert drafter.tree_lanes.num_slots == 44
+ assert drafter.lanes_per_request == 4
+ assert not drafter.draft_model_runner.model.logits_processor.do_argmax
+
+
+def _kernel_drafter(
+ cost: BatchCostTable, scale: torch.Tensor, sleep: bool
+) -> EagleHarness:
+ """A drafter of K=2 trees to depth 6 on the device policy and the real
+ pool, ranking and verify tree kernels, its depths captured; its draft
+ forward is scripted from its inputs and the round's ``scale``, and with
+ ``sleep`` runs long."""
+ drafter, k = _drafter(), TREE_K
+ del drafter._draft_depth
+ drafter.config = HarnessConfig(mode=Mode.SERVE, data_path="/unused")
+ drafter.spec_num_steps = TREE_DEPTH
+ drafter.device = torch.device("cuda")
+ drafter.policy = DevicePolicy(
+ policy_costs(
+ {bs: replace(cost, batch_size=bs) for bs in (1, 2)},
+ k=k,
+ depth=TREE_DEPTH,
+ verify=WINDOW,
+ moe=False,
+ ),
+ verify_num=WINDOW,
+ node_top_k=k,
+ tree_depth=TREE_DEPTH,
+ compute_intensity="high_intensity",
+ is_moe_target=False,
+ exec_mode=0,
+ benchmark_config="",
+ chain_width_table=(),
+ device=drafter.device,
+ )
+ drafter.lanes_per_request = k
+ drafter.tree_lanes = TreeDraftInputs(k, TREE_DEPTH, BS, drafter.device)
+ drafter.token_to_kv_pool = None
+ drafter.attn_backend = SimpleNamespace(
+ publish_draft_step_locations=lambda **kw: None,
+ override_num_extends=lambda n: contextlib.nullcontext(),
+ begin_tree_lanes=lambda rows, live_rows: None,
+ )
+
+ def forward(input_ids, positions, captured_hidden_states, spec_step_idx, **kw):
+ if sleep:
+ torch.cuda._sleep(50_000_000)
+ base = (input_ids * 31 + positions * 7 + spec_step_idx) % 997
+ steps = torch.arange(k, device="cuda")
+ probs = torch.sigmoid(scale * torch.sin(base[:, None] + steps).float())
+ return SimpleNamespace(
+ draft_topk=(
+ probs.sort(dim=1, descending=True).values,
+ (base[:, None] * 13 + steps * 101) % 5000,
+ ),
+ hidden_states=captured_hidden_states * 0.5 + 1,
+ )
+
+ drafter.draft_model_runner = SimpleNamespace(
+ model=SimpleNamespace(config=SimpleNamespace(hidden_size=HIDDEN)),
+ model_config=SimpleNamespace(dtype=torch.float32),
+ forward=forward,
+ )
+ drafter.round_candidates = lambda rows: rows.draft_topk
+ drafter._allocate(BS, k, TREE_DEPTH, 1024, 64)
+ drafter._depth_graphs, drafter._finalize_graphs = {}, {}
+ drafter.capture_round_graphs(BS, lo_bs=0, stream=torch.cuda.Stream(), pool=None)
+ return drafter
+
+
+def _seed_round(drafter: EagleHarness, inputs: dict[str, torch.Tensor]) -> None:
+ """What ``draft`` leaves for depth 1 inside the decode graph: the root,
+ its children in the pool and depth 1's frontier and lanes."""
+ pool, state = drafter._pool, drafter._round
+ pool["tokens"][:BS, 0] = inputs["root"]
+ drafter_module.eagle_harness_update_node_data(
+ pool["scores"][:BS],
+ pool["tokens"][:BS],
+ pool["work"][:BS],
+ pool["sort"][:BS],
+ inputs["top_p"],
+ inputs["top_tokens"],
+ )
+ state["root_tokens"][:BS].copy_(inputs["root"])
+ state["tokens"][:BS].copy_(inputs["top_tokens"])
+ state["scores"][:BS].copy_(inputs["top_p"])
+ state["hidden"][:BS].copy_(inputs["hidden"])
+ state["frontier"][:BS].copy_(inputs["frontier"])
+ state["rows"][:BS].copy_(inputs["rows"])
+ drafter._start_lanes(BS, BS)
+
+
[email protected](not torch.cuda.is_available(), reason="needs CUDA")
+def test_a_device_chained_round_drafts_the_host_launched_round() -> None:
+ """Rounds whose depths and finalize the GPU chains, launched behind a
+ decode graph or by ``finish_round``, grow the same pool, publish the same
+ go flags and decisions and write the same verify tree as rounds whose
+ depths the host launches one by one, also once their graphs were
+ released and captured again; behind a decode graph, the forward's stream
+ waits for that whole graph and not for the round."""
+ target = CostCurve(
+ (1.0,) * 5, (1.0, 1.02, 1.05, 1.1, 1.3), (0, 1, 3, 7, 15), (), ()
+ )
+ draft = CostCurve((1.0, 1.0), (1.0, 1.2), (0, 1), (), ())
+ cost = BatchCostTable(
+ 1, 1000, 1000, 16, 16384, 2, (IntervalCost(target, draft),), (20.0,)
+ )
+ scale = torch.ones((), device="cuda")
+ host, launched, behind = (
+ _kernel_drafter(cost, scale, sleep) for sleep in (False, False, True)
+ )
+ inputs = {
+ "root": torch.zeros(BS, dtype=torch.int64, device="cuda"),
+ "top_p": torch.zeros((BS, TREE_K), device="cuda"),
+ "top_tokens": torch.zeros((BS, TREE_K), dtype=torch.int64, device="cuda"),
+ "hidden": torch.zeros((BS, TREE_K, HIDDEN), device="cuda"),
+ "frontier": torch.zeros(BS, dtype=torch.int64, device="cuda"),
+ "rows": torch.arange(BS, device="cuda"),
+ }
+ # The decode graph a chained round follows: the draft's seeding, then a
+ # slow tail whose result the forward's stream reads.
+ tail = torch.zeros(1, dtype=torch.int64, device="cuda")
+ decode = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(decode):
+ _seed_round(behind, inputs)
+ torch.cuda._sleep(20_000_000)
+ tail.copy_(inputs["frontier"][:1])
+ ctx = SimpleNamespace(bs=BS, num_extends=0, global_num_tokens=None, global_bs=None)
+ ctx.all_decode_or_idle = True
+ depths = set()
+ for i in range(12):
+ if i == 10:
+ for drafter in (host, launched, behind):
+ drafter.release_round_graphs()
+ drafter.capture_round_graphs(
+ BS, lo_bs=0, stream=torch.cuda.Stream(), pool=None
+ )
+ gen = torch.Generator().manual_seed(i)
+ scale.fill_(0.5 + 0.4 * i)
+ inputs["root"].copy_(torch.randint(0, 5000, (BS,), generator=gen))
+ inputs["top_p"].copy_(
+ torch.rand((BS, TREE_K), generator=gen).sort(dim=1, descending=True).values
+ )
+ inputs["top_tokens"].copy_(torch.randint(0, 5000, (BS, TREE_K), generator=gen))
+ inputs["hidden"].copy_(torch.rand((BS, TREE_K, HIDDEN), generator=gen))
+ inputs["frontier"].copy_(torch.tensor([100 + 37 * i, 900 + 11 * i]))
+ for drafter, graph_bs in ((host, None), (launched, BS)):
+ _seed_round(drafter, inputs)
+ drafter.finish_round(ctx, graph_bs)
+ drafter.complete_round()
+ behind.replay_decode_graph(decode, bs=BS, graph_bs=BS)
+ tail_seen = tail.clone()
+ seeded = torch.cuda.Event()
+ seeded.record()
+ behind.finish_round(ctx, BS)
+ seeded.synchronize()
+ # The forward's stream ran past the decode graph while the round drafts.
+ assert not behind._round_stream.query()
+ behind.complete_round()
+ assert not torch.cuda.current_stream().query()
+ torch.cuda.synchronize()
+ assert tail_seen.item() == 100 + 37 * i
+ depths.add(host.policy.last_depth.item())
+ expected = _round_outputs(host)
+ for drafter in (launched, behind):
+ outputs = _round_outputs(drafter)
+ assert outputs.keys() == expected.keys()
+ for name, value in expected.items():
+ assert torch.equal(outputs[name], value), (i, name)
+ # Rounds stopped at several depths, the deepest at the last.
+ assert len(depths) > 2 and TREE_DEPTH - 1 in depths
+
+
+def _round_outputs(drafter: EagleHarness) -> dict[str, torch.Tensor]:
+ """What a round leaves: its pool and round buffers, the policy's state,
+ slots (go flags included) and their tagged host mirror, and the verify
+ tree."""
+ policy = drafter.policy
+ return {
+ **{f"pool.{name}": value for name, value in drafter._pool.items()},
+ **{f"round.{name}": value for name, value in drafter._round.items()},
+ "state": policy._state,
+ "slots": policy._slots,
+ "go_host": policy.go_host,
+ "tree": drafter.runtime_states.future_input_map,
+ "parents": drafter.runtime_states.future_parent_map,
+ }
+
+
+def test_release_round_graphs_drops_what_named_the_probe_pool() -> None:
+ """Graphs recorded on the probe pool must not survive the recapture."""
+ harness = EagleHarness.__new__(EagleHarness)
+ harness._chain = None
+ harness._depth_graphs = {(1, 1): object()}
+ harness._finalize_graphs = {(1, False): object()}
+ harness.release_round_graphs()
+ assert harness._depth_graphs == {} and harness._finalize_graphs == {}
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, *sys.argv[1:]]))
diff --git a/tests/tokenspeed_round/test_feature_regressions_gpu.py b/tests/tokenspeed_round/test_feature_regressions_gpu.py
new file mode 100644
index 0000000..2e1f367
--- /dev/null
+++ b/tests/tokenspeed_round/test_feature_regressions_gpu.py
@@ -0,0 +1,86 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Regressions at the real policy/round boundary, without model weights."""
+
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+pytest.importorskip("tvm_ffi", reason="TokenSpeed round kernels require apache-tvm-ffi")
+
+from tests.tokenspeed_round.test_chain_sampled_policy_gpu import (
+ capture_round,
+ chain_policy,
+ replay,
+)
+
+if not torch.cuda.is_available():
+ pytest.skip("needs CUDA", allow_module_level=True)
+
+pytest.importorskip("tokenspeed", reason="requires the optional TokenSpeed engine")
+
+
+
+from tokenspeed.runtime.sampling.sampling_params import SamplingParams
+
+from eagle_harness.tokenspeed.tree_round.device_policy import DevicePolicy
+from eagle_harness.tokenspeed.tree_round.dynamic import DynamicDrafter
+
+pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA")
+
+
+def test_fully_scheduled_chain_enters_native_policy_without_costs():
+ policy = DevicePolicy(
+ None,
+ verify_num=8,
+ node_top_k=1,
+ tree_depth=7,
+ compute_intensity="chain_intensity",
+ is_moe_target=False,
+ exec_mode=0,
+ benchmark_config="",
+ chain_width_table=((1, 4),),
+ device=torch.device("cuda"),
+ )
+ inputs = capture_round(policy)
+ for sample in (False, True):
+ for batch in (1, 33, 512):
+ replay(inputs, batch=batch, gain=0.0, sample=sample)
+ assert policy.verify_num.item() == 4
+ assert policy.last_depth.item() == 2
+
+
+def test_idle_policy_warmups_do_not_advance_the_first_live_sequence():
+ policy = chain_policy()
+ inputs = capture_round(policy)
+ for _ in range(3):
+ replay(inputs, batch=0, gain=0.0, sample=False)
+ replay(inputs, batch=1, gain=0.0, sample=False)
+ assert policy.go_ready(3, 1) is False
+ replay(inputs, batch=1, gain=100000.0, sample=False)
+ assert policy.go_ready(3, 2) is True
+
+
+def test_discarded_prefill_is_not_a_live_policy_round():
+ # Only the absent model/engine allocation is replaced. Real preparation and
+ # policy kernels must use the same round count as finish_round's skip rule.
+ drafter = DynamicDrafter.__new__(DynamicDrafter)
+ drafter.policy = chain_policy()
+ drafter._sampled_q = object()
+ drafter._live_rows = 0
+ drafter._live_sampled = False
+ drafter.input_buffers = SimpleNamespace(all_extends_mid_chunk=True)
+ drafter._round = {
+ "live_rows": torch.zeros(1, dtype=torch.int32, device="cuda"),
+ "sampled": torch.zeros(1, dtype=torch.bool, device="cuda"),
+ }
+ param = SamplingParams(temperature=1.0, seed=11)
+ param.normalize(None)
+ drafter.prepare_round_sampling([param])
+ assert drafter._round["live_rows"].item() == 0
+ drafter.input_buffers.all_extends_mid_chunk = False
+ drafter.prepare_round_sampling([param])
+ assert drafter._round["live_rows"].item() == 1
+ assert drafter._round["sampled"].item()
diff --git a/tests/tokenspeed_round/test_ops_build.py b/tests/tokenspeed_round/test_ops_build.py
new file mode 100644
index 0000000..c876531
--- /dev/null
+++ b/tests/tokenspeed_round/test_ops_build.py
@@ -0,0 +1,98 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""CPU checks for CUDA compilation, including device-runtime linking."""
+
+import subprocess
+import sys
+from pathlib import Path
+from subprocess import CompletedProcess
+
+import pytest
+
+from eagle_harness.tokenspeed.tree_round.ops import build
+
+
+def test_builder_import_does_not_load_torch_or_tokenspeed():
+ subprocess.run(
+ [sys.executable, "-c", (
+ "import sys; from eagle_harness.tokenspeed.tree_round.ops import build; "
+ "assert 'torch' not in sys.modules; assert 'tokenspeed' not in sys.modules"
+ )],
+ check=True,
+ )
+
+
+def test_explicit_toolkit_discovery_and_version(tmp_path):
+ toolkit = tmp_path / "cuda"
+ compiler = toolkit / "bin" / "nvcc"
+ compiler.parent.mkdir(parents=True)
+ compiler.write_text(
+ "#!/bin/sh\nprintf 'Cuda compilation tools, release 13.0, V13.0.1\\n'\n"
+ )
+ compiler.chmod(0o755)
+ assert build.find_nvcc(str(toolkit)) == str(compiler)
+ assert build.toolkit_version(str(compiler)) == (13, 0)
+ compiler.write_text("#!/bin/sh\nprintf 'unknown compiler\\n'\n")
+ with pytest.raises(RuntimeError, match="cannot read the CUDA version"):
+ build.toolkit_version(str(compiler))
+
+
[email protected]("name", build.MODULES)
+def test_compile_recipe_and_atomic_publication(tmp_path, monkeypatch, name):
+ commands = []
+ monkeypatch.setattr(build, "toolkit_version", lambda _: (13, 0))
+ monkeypatch.setattr(
+ build,
+ "_ffi_paths",
+ lambda: (["/ffi/include", "/dlpack/include"], "/ffi/lib/libtvm_ffi.so"),
+ )
+ out = tmp_path / f"{name}.so"
+ out.write_bytes(b"previous")
+
+ def run(command, **kwargs):
+ commands.append(command)
+ # The published artifact is untouched throughout compilation and linking.
+ assert out.read_bytes() == b"previous"
+ Path(command[command.index("-o") + 1]).write_bytes(b"built")
+ return CompletedProcess(command, returncode=0, stdout="", stderr="")
+
+ monkeypatch.setattr(build.subprocess, "run", run)
+ assert build.compile_library(name, out, 103, "/cuda/bin/nvcc") == out
+ assert out.read_bytes() == b"built"
+ assert "--fmad=false" in commands[0]
+ assert "--expt-relaxed-constexpr" in commands[0]
+ assert not any("-use_fast_math" in command for command in commands)
+ assert "-I/dlpack/include" in commands[0]
+ assert "-gencode=arch=compute_103,code=sm_103" in commands[0]
+ assert "-gencode=arch=compute_103,code=compute_103" in commands[0]
+ assert "-cudart=static" in commands[-1]
+ if name == "chain":
+ assert len(commands) == 3
+ assert "-rdc=true" in commands[0]
+ assert "-dlink" in commands[1]
+ assert "-lcudadevrt" in commands[1] and "-lcudadevrt" in commands[2]
+ assert any(p.endswith("device_link.o") for p in commands[2])
+ else:
+ assert len(commands) == 2
+ assert list(tmp_path.iterdir()) == [out]
+
+
+def test_failed_build_preserves_existing_library(tmp_path, monkeypatch):
+ monkeypatch.setattr(build, "toolkit_version", lambda _: (13, 0))
+ monkeypatch.setattr(
+ build, "_ffi_paths", lambda: (["/ffi/include"], "/ffi/lib/libtvm_ffi.so")
+ )
+ monkeypatch.setattr(
+ build.subprocess,
+ "run",
+ lambda *a, **kw: CompletedProcess(
+ a[0], returncode=1, stdout="", stderr="deliberate compiler failure"
+ ),
+ )
+ out = tmp_path / "policy.so"
+ out.write_bytes(b"old")
+ with pytest.raises(RuntimeError, match="deliberate compiler failure"):
+ build.compile_library("policy", out, 103, "nvcc")
+ assert out.read_bytes() == b"old"
+ assert list(tmp_path.iterdir()) == [out]
diff --git a/tests/tokenspeed_round/test_policy_cost.py b/tests/tokenspeed_round/test_policy_cost.py
new file mode 100644
index 0000000..2792f16
--- /dev/null
+++ b/tests/tokenspeed_round/test_policy_cost.py
@@ -0,0 +1,194 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Exact CPU packing and validation of caller-owned structural cost records."""
+
+from dataclasses import replace
+
+import pytest
+import torch
+
+from eagle_harness.tokenspeed.tree_round.device_policy import (
+ DevicePolicy,
+ write_round_slots,
+)
+from eagle_harness.tokenspeed.tree_round.policy_cost import build_tables
+from tests.tokenspeed_round.cost_records import records
+
+
+def test_pack_records_without_policy_recomputation():
+ costs = records()
+ tables = build_tables(costs, device=torch.device("cpu"))
+ assert tables.interval_i32.dtype == torch.int32
+ assert tables.interval_f64.dtype == torch.float64
+ assert tables.batch_table.dtype == torch.int64
+ assert tables.tier_table.dtype == torch.int32
+ assert tables.verify_i32.dtype == torch.int32
+ assert tables.verify_f64.dtype == torch.float64
+ assert tables.interval_i32.shape == (2, 2, 4)
+ assert tables.interval_f64.shape == (2, 2, 21)
+ assert tables.tier_table.tolist() == [16, 8, 4, 2, 32, 2, 2, 2, 2]
+ assert tables.interval_i32[0].tolist() == [[2, 0, 3, 0], [0, 0, 0, 0]]
+ assert torch.count_nonzero(tables.interval_f64[0, 1]) == 0
+ for live, batch in enumerate(costs.batches):
+ cost_id = live % 2
+ assert tables.batch_table[live].tolist() == [
+ cost_id,
+ 0,
+ len(batch.intervals),
+ batch.cache_length_step,
+ 0,
+ ]
+ for i, interval in enumerate(batch.intervals):
+ n = len(interval.verify_widths)
+ packed = tables.interval_f64[cost_id, i]
+ assert packed[:2].tolist() == [
+ interval.draft_cost,
+ interval.model_cost_ratio,
+ ]
+ assert packed[2:12].view(5, 2).tolist() == [
+ list(row) for row in interval.depth_thresholds
+ ]
+ delta = packed[12:].view(3, 3)
+ assert delta[:n, :n].tolist() == [
+ list(row) for row in interval.verify_cost_deltas
+ ]
+ assert torch.count_nonzero(delta[n:]) == 0
+ assert torch.count_nonzero(delta[:, n:]) == 0
+ assert tables.verify_i32[live, i].item() == interval.verify_tier
+ assert tables.verify_f64[live, i].tolist() == list(
+ interval.verify_thresholds
+ )
+ if len(batch.intervals) == 1:
+ assert tables.verify_i32[live, 1] == 0
+ assert torch.count_nonzero(tables.verify_f64[live, 1]) == 0
+
+
+ "change",
+ [
+ {"batches": ()},
+ {"history_floors": (1,)},
+ {"initial_widths": (1,)},
+ {"history_floors": (16, 8, 4, 2, 2**31)},
+ {"initial_widths": (2, 2, 2, 9)},
+ {"async_layer_ratio": float("nan")},
+ {"async_layer_ratio": 0.0},
+ ],
+)
+def test_invalid_cost_records_rejected(change):
+ with pytest.raises(ValueError):
+ build_tables(replace(records(), **change), device=torch.device("cpu"))
+
+
+ "change",
+ [
+ {"cost_batch_size": 0},
+ {"cache_length_step": 0},
+ {"cache_length_step": -1},
+ {"cache_length_step": 2**63},
+ {"intervals": ()},
+ ],
+)
+def test_invalid_batch_rejected(change):
+ costs = records()
+ costs = replace(
+ costs, batches=(replace(costs.batches[0], **change), *costs.batches[1:])
+ )
+ with pytest.raises(ValueError):
+ build_tables(costs, device=torch.device("cpu"))
+
+
+ "change",
+ [
+ {"verify_widths": (1, 3)},
+ {"verify_widths": (0, 3, 1)},
+ {"verify_widths": (0, 1, 1)},
+ {"verify_widths": (0, 2**31)},
+ {"verify_widths": tuple(range(33))},
+ {"draft_cost": 0.0},
+ {"draft_cost": float("nan")},
+ {"model_cost_ratio": 4.9},
+ {"model_cost_ratio": 101.0},
+ {"model_cost_ratio": float("nan")},
+ {"depth_thresholds": ()},
+ {"depth_thresholds": ((0.1,),) * 5},
+ {"depth_thresholds": ((0.1, float("nan")),) * 5},
+ {"verify_cost_deltas": ((0.0, -0.1), (0.0, 0.0))},
+ {"verify_cost_deltas": ((0.0,),)},
+ {"verify_tier": 4},
+ {"verify_thresholds": (0.0, 1.0)},
+ ],
+)
+def test_invalid_interval_rejected(change):
+ costs = records()
+ batch = costs.batches[0]
+ batch = replace(batch, intervals=(replace(batch.intervals[0], **change),))
+ with pytest.raises(ValueError):
+ build_tables(
+ replace(costs, batches=(batch, *costs.batches[1:])),
+ device=torch.device("cpu"),
+ )
+
+
+def test_conflicting_measured_rows_cannot_be_silently_discarded():
+ costs = records()
+ batch = costs.batches[2]
+ batch = replace(batch, intervals=(replace(batch.intervals[0], draft_cost=9.0),))
+ with pytest.raises(ValueError, match="conflicting costs"):
+ build_tables(
+ replace(costs, batches=(*costs.batches[:2], batch, *costs.batches[3:])),
+ device=torch.device("cpu"),
+ )
+
+
+ "change",
+ [
+ {"node_top_k": 1},
+ {"node_top_k": 3},
+ {"node_top_k": 16},
+ {"tree_depth": 1},
+ {"tree_depth": 33},
+ {"tree_depth": 18},
+ {"verify_num": 1},
+ {"verify_num": 65},
+ {"compute_intensity": "chain_intensity"},
+ {"exec_mode": 1},
+ {"exec_mode": 2},
+ {"benchmark_config": "unsupported"},
+ {"chain_width_table": ((1, 4),)},
+ {"device": torch.device("cpu")},
+ ],
+)
+def test_unsupported_policy_rejected_without_build(change):
+ config = {
+ "verify_num": 32,
+ "node_top_k": 4,
+ "tree_depth": 8,
+ "compute_intensity": "high_intensity",
+ "is_moe_target": False,
+ "exec_mode": 0,
+ "benchmark_config": "",
+ "chain_width_table": (),
+ "device": torch.device("cuda"),
+ }
+ config.update(change)
+ with pytest.raises(ValueError):
+ DevicePolicy(records(), **config)
+
+
+def test_warmup_slots():
+ slots = torch.full((4, 5), -1, dtype=torch.int32)
+ count = write_round_slots(
+ slots, 4, [4, 2, 2], lambda d, n: min(n, 16) if d % 2 == 0 else 0
+ )
+ assert count == 37
+ assert slots.tolist() == [
+ [0, 4, 2, 2, 0],
+ [0, 5, 21, 29, 0],
+ [0, 0, 16, 0, 0],
+ [0, 1, 1, 1, 0],
+ ]
diff --git a/tests/tokenspeed_round/test_policy_ops_gpu.py b/tests/tokenspeed_round/test_policy_ops_gpu.py
new file mode 100644
index 0000000..11e3578
--- /dev/null
+++ b/tests/tokenspeed_round/test_policy_ops_gpu.py
@@ -0,0 +1,68 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""EAGLE-Harness device policy kernels: the cumulative ranked scores against
+torch's, bit for bit, at every shape the policy ranks."""
+
+import sys
+
+import pytest
+import torch
+
+pytest.importorskip("tvm_ffi", reason="TokenSpeed round kernels require apache-tvm-ffi")
+
+from eagle_harness.tokenspeed.tree_round.ops.policy import (
+ eagle_harness_ranked_scores,
+)
+
+pytestmark = pytest.mark.skipif(
+ not torch.cuda.is_available(), reason="CUDA GPU is required"
+)
+
+_DEVICE = "cuda"
+_MAX_ROWS, _MAX_COLS = 32, 64
+
+
+def _ranked_rows(
+ rows: int, cols: int, binades: int, generator: torch.Generator
+) -> torch.Tensor:
+ """Each row's scores in rank order: descending scores in (0, 1) spread
+ over ``binades`` binades (many: sums in another order round apart)."""
+ scores = torch.rand((rows, cols), generator=generator, dtype=torch.float64)
+ scale = torch.exp2(-torch.randint(0, binades, (rows, cols), generator=generator))
+ return (scores * scale).float().sort(dim=-1, descending=True).values
+
+
[email protected]("flat", [False, True])
+def test_ranked_scores_match_torch(flat: bool) -> None:
+ generator = torch.Generator().manual_seed(int(flat))
+ # The kernel reads the live corner of a padded buffer.
+ buffer = torch.full((_MAX_ROWS + 3, _MAX_COLS + 5), float("nan"), device=_DEVICE)
+ out = torch.empty(_MAX_ROWS * _MAX_COLS, device=_DEVICE)
+ sizes = torch.empty(4, dtype=torch.int32, device=_DEVICE)
+ rows_t, cols_t, flat_t, count = sizes.split(1)
+ flat_t.fill_(int(flat))
+ shapes, mismatches = [], []
+ for binades in (1, 24):
+ for rows in range(1, _MAX_ROWS + 1):
+ for cols in range(1, _MAX_COLS + 1):
+ shapes.append((binades, rows, cols))
+ top = _ranked_rows(rows, cols, binades, generator).to(_DEVICE)
+ expected = torch.cumsum(
+ top.view(-1) if flat else top.mean(dim=0), dim=0
+ )
+ buffer[:rows, :cols] = top
+ rows_t.fill_(rows)
+ cols_t.fill_(cols)
+ eagle_harness_ranked_scores(buffer, rows_t, cols_t, flat_t, out, count)
+ n = expected.numel()
+ mismatches.append(
+ (count[0] != n)
+ | (out[:n].view(torch.int32) != expected.view(torch.int32)).any()
+ )
+ failed = torch.stack(mismatches).nonzero().flatten().tolist()
+ assert not failed, f"(binades, rows, cols) {[shapes[i] for i in failed[:5]]}"
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, *sys.argv[1:]]))
diff --git a/tests/tokenspeed_round/test_rejection_kernel_gpu.py b/tests/tokenspeed_round/test_rejection_kernel_gpu.py
new file mode 100644
index 0000000..2744b69
--- /dev/null
+++ b/tests/tokenspeed_round/test_rejection_kernel_gpu.py
@@ -0,0 +1,140 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+
+"""Generic tree rejection and residual sampling against probability references."""
+
+import pytest
+import torch
+
+pytest.importorskip("tokenspeed_kernel")
+from tokenspeed_kernel.platform import current_platform
+from eagle_harness.tokenspeed.tree_round.ops.rejection import (
+ residual_sample,
+ tree_reject_sample,
+)
+
+pytestmark = pytest.mark.skipif(
+ not torch.cuda.is_available() or not current_platform().is_nvidia,
+ reason="tree rejection CUDA kernels are NVIDIA-only",
+)
+
+_DEVICE = "cuda"
+
+
+def test_deterministic_children_emit_the_target_distribution() -> None:
+ """Children without a draft q are accepted by p'(child) over the mass their
+ rejected siblings left: with the residual bonus the first token's law is
+ the root's target."""
+ vocab, bs, trials = 16, 8192, 24
+ generator = torch.Generator().manual_seed(1)
+ target = torch.softmax(torch.randn(vocab, generator=generator) * 1.5, dim=-1)
+ second, best = torch.topk(target, 2).indices.tolist()[::-1]
+ tokens = torch.tensor([0, second, best], dtype=torch.int32, device=_DEVICE)
+ tokens = tokens.repeat(bs, 1)
+ parents = torch.tensor([-1, 0, 0], dtype=torch.int32, device=_DEVICE).repeat(bs, 1)
+ q_tables = (
+ torch.full((1, 3), -1, dtype=torch.int32, device=_DEVICE),
+ torch.zeros((1, 3), dtype=torch.int32, device=_DEVICE),
+ torch.zeros((1, 1, 1), device=_DEVICE),
+ torch.zeros((1, 1, 1), dtype=torch.int32, device=_DEVICE),
+ )
+ unread = torch.full((bs * 3,), -1, dtype=torch.int64, device=_DEVICE)
+ probas = target.to(_DEVICE).repeat(bs * 3, 1)
+ first = torch.zeros(vocab)
+ for _ in range(trials):
+ _, predicts, _, _ = _verify(
+ probas.clone(), tokens, parents, None, q_tables,
+ torch.rand((bs, 3), device=_DEVICE), torch.rand(bs, device=_DEVICE),
+ _no_top_k(bs * 3), unread,
+ ) # fmt: skip
+ first += torch.bincount(predicts[:, 0].long().cpu(), minlength=vocab).float()
+ torch.testing.assert_close(first / (bs * trials), target, rtol=0, atol=0.005)
+
+
+def _no_top_k(rows: int) -> torch.Tensor:
+ """Per-row top-k of sampled (never greedy) rows."""
+ return torch.full((rows,), 1 << 30, dtype=torch.int32, device=_DEVICE)
+
+
+def _verify(probas, tokens, parents, q_rows, q_tables, coins, final_coins, top_ks, argmax):
+ """Rejection-sample each request's tree, then draw its bonus: path,
+ predicts (``[bs, N]``), accept length and last row."""
+ bs, n = tokens.shape
+ path = torch.empty((bs, n), dtype=torch.int32, device=_DEVICE)
+ predicts = torch.full((bs * n,), -1, dtype=torch.int32, device=_DEVICE)
+ accept_length = torch.empty(bs, dtype=torch.int32, device=_DEVICE)
+ last_row = torch.empty(bs, dtype=torch.int64, device=_DEVICE)
+ tree_reject_sample(
+ probas, tokens, parents, q_rows, *q_tables, coins, top_ks, argmax, path,
+ predicts, accept_length, last_row,
+ ) # fmt: skip
+ residual_sample(probas, last_row, final_coins, top_ks, argmax, accept_length, predicts, n)
+ return path, predicts.view(bs, n), accept_length, last_row
+
+
+def _verify_sampled(probas, tokens, parents, q_tables, coins, final_coins):
+ """``_verify`` of sampled rows, q tables at the requests' own rows; the
+ argmax is the kernels' own, read from probas."""
+ bs, n = tokens.shape
+ unread = torch.full((bs * n,), -1, dtype=torch.int64, device=_DEVICE)
+ _, predicts, accept_length, _ = _verify(
+ probas, tokens, parents, torch.arange(bs, device=_DEVICE), q_tables, coins,
+ final_coins, _no_top_k(bs * n), unread,
+ ) # fmt: skip
+ return predicts, accept_length
+
+
+def test_vanished_residual_takes_the_rows_first_argmax() -> None:
+ """A sampled row whose residual vanishes takes torch.argmax of its target
+ row as the bonus, although the rejection already lowered that entry: the
+ drawn child (p = 0) is rejected, and q equal to p on the other candidates
+ leaves no residual. The target ties at tokens 50 and 20 (q position 0 and
+ 1): the lower token wins."""
+ bs, vocab, nc = 64, 300, 16
+ ids = torch.arange(nc, dtype=torch.int32, device=_DEVICE)
+ ids[:4] = torch.tensor([50, 20, 80, 9], dtype=torch.int32)
+ q = torch.zeros(nc, device=_DEVICE)
+ q[:4] = torch.tensor([0.375, 0.375, 0.25 - 3.0e-8, 3.0e-8])
+
+ def rows(values: list[int]) -> torch.Tensor:
+ return torch.tensor(values, dtype=torch.int32, device=_DEVICE).repeat(bs, 1)
+
+ # A root (token 7) and one child (token 9) drawn from q (slot 0, position 3).
+ tokens, parents = rows([7, 9]), rows([-1, 0])
+ q_tables = (rows([-1, 0]), rows([0, 3]), q.repeat(bs, 1, 1), ids.repeat(bs, 1, 1))
+ probas = torch.zeros((bs * 2, vocab), device=_DEVICE)
+ probas[:, [50, 20, 80]] = torch.tensor([0.375, 0.375, 0.25], device=_DEVICE)
+ coins = torch.rand((bs, 2), device=_DEVICE)
+ # Final coins below 0.99: the bonus row's 3e-8 residual left on token 80 is never drawn.
+ predicts, accept_length = _verify_sampled(
+ probas, tokens, parents, q_tables, coins, torch.rand(bs, device=_DEVICE) * 0.99
+ )
+ assert (accept_length == 1).all() and (predicts[:, 0] == 20).all()
+ # The root's row: its argmax set to 1 over the vanished residual.
+ assert (probas[0::2, 20] == 1.0).all() and (probas[0::2, 50] < 1e-6).all()
+
+
[email protected]("vocab", [151936, 40001])
+def test_residual_bonus_inverts_the_cdf_of_a_wide_row(vocab: int) -> None:
+ """Wide rows stage each thread's segment in several runs: the bonus is the
+ token whose CDF interval holds the coin (aimed at interval middles, clear
+ of rounding), over an unnormalized row."""
+ bs, n, positive = 16, 4, 64
+ gen = torch.Generator().manual_seed(vocab)
+ probas = torch.zeros((bs * n, vocab))
+ idx = torch.stack([torch.randperm(vocab, generator=gen)[:positive] for _ in range(bs * n)])
+ probas.scatter_(1, idx, torch.rand((bs * n, positive), generator=gen) + 0.5)
+ last_row = torch.arange(bs) * n + torch.randint(0, n, (bs,), generator=gen)
+ expected = idx[last_row, torch.randint(0, positive, (bs,), generator=gen)]
+ rows = probas[last_row].double()
+ mass = rows.gather(1, expected[:, None]).squeeze(1)
+ below = rows.cumsum(-1).gather(1, expected[:, None]).squeeze(1) - mass
+ coins = ((below + 0.5 * mass) / rows.sum(-1)).float()
+ predicts = torch.full((bs * n,), -1, dtype=torch.int32, device=_DEVICE)
+ residual_sample(
+ probas.to(_DEVICE), last_row.to(_DEVICE), coins.to(_DEVICE),
+ _no_top_k(bs * n), torch.full((bs * n,), -1, dtype=torch.int64, device=_DEVICE),
+ torch.full((bs,), n, dtype=torch.int32, device=_DEVICE), predicts, n,
+ ) # fmt: skip
+ assert torch.equal(predicts.view(bs, n)[:, -1].cpu().long(), expected)
diff --git a/tests/tokenspeed_round/test_sampled_chain_round_gpu.py b/tests/tokenspeed_round/test_sampled_chain_round_gpu.py
new file mode 100644
index 0000000..4a7705a
--- /dev/null
+++ b/tests/tokenspeed_round/test_sampled_chain_round_gpu.py
@@ -0,0 +1,268 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Full deferred chain rounds with a weight-free candidate-head forward."""
+
+import contextlib
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+pytest.importorskip("tvm_ffi", reason="TokenSpeed round kernels require apache-tvm-ffi")
+
+from tests.tokenspeed_round.chain_cost_records import records
+from tests.tokenspeed_round.test_dynamic_gpu import _drafter
+
+if not torch.cuda.is_available():
+ pytest.skip("needs CUDA", allow_module_level=True)
+
+from eagle_harness.tokenspeed.hooks import sampled_hook_problems
+
+if sampled_hook_problems():
+ pytest.skip("engine lacks recorded-proposal hooks", allow_module_level=True)
+
+from tokenspeed.runtime.execution.input_buffer import InputBuffers
+from tokenspeed.runtime.execution.runtime_states import RuntimeStates
+from tokenspeed.runtime.sampling.backends.base import SamplingBackendConfig
+from tokenspeed.runtime.sampling.backends.flashinfer import FlashInferSamplingBackend
+from tokenspeed.runtime.sampling.sampling_params import SamplingParams
+
+from eagle_harness.tokenspeed.models import CandidateRows
+from eagle_harness.tokenspeed.tree_round.device_policy import DevicePolicy
+
+pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA")
+
+
+def _chain(capacity, scheduled):
+ drafter = _drafter()
+ del drafter._draft_depth
+ device = drafter.device = torch.device("cuda")
+ drafter.spec_num_steps, drafter.spec_num_tokens = 7, 8
+ drafter.draft_reads_token_history = False
+ drafter._depth_graphs, drafter._finalize_graphs = {}, {}
+ drafter._sampled = {}
+ drafter._sampling_backend = None
+ drafter.token_to_kv_pool = None
+ drafter.input_buffers = InputBuffers(capacity, capacity * 8, 0, device=device)
+ slots = torch.arange(1, capacity + 1, device=device)
+ drafter.input_buffers.req_pool_indices_buf.copy_(slots)
+ drafter.input_buffers.state_write_req_pool_indices_buf.copy_(slots)
+ drafter.input_buffers.seq_lens_buf.fill_(128)
+ drafter.padded_gather_ids_offsets_buf = (
+ torch.arange(capacity, device=device) * 8 - 1
+ )
+ drafter.attn_backend = SimpleNamespace(
+ bind_tree_draft=lambda tree: None,
+ publish_draft_step_locations=lambda **kw: None,
+ override_num_extends=lambda n: contextlib.nullcontext(),
+ begin_tree_lanes=lambda rows, live_rows: None,
+ )
+ head_logits = -torch.arange(4, dtype=torch.float32, device=device)
+ head_ids = torch.arange(2, 6, device=device)
+
+ def forward(input_ids, captured_hidden_states, **kw):
+ rows = input_ids.numel()
+ return CandidateRows(
+ next_token_logits=head_logits.expand(rows, 4).contiguous(),
+ candidate_ids=head_ids.expand(rows, 4).contiguous(),
+ hidden_states=captured_hidden_states * 0.5 + 1,
+ )
+
+ drafter.draft_model_runner = SimpleNamespace(
+ model=SimpleNamespace(
+ config=SimpleNamespace(hidden_size=8),
+ logits_processor=SimpleNamespace(
+ do_argmax=True, config=SimpleNamespace(vocab_size=32)
+ ),
+ ),
+ model_config=SimpleNamespace(dtype=torch.float32),
+ forward=forward,
+ )
+ drafter.round_candidates = lambda out: (
+ out.next_token_logits.softmax(-1)[:, :1].clone(),
+ out.candidate_ids[:, :1].clone(),
+ )
+ # The target/step-0 model forward is the only part replaced by this fixture.
+ drafter._run_first_step = lambda bs, inputs, narrowing: (
+ forward(
+ input_ids=inputs.base_model_output[:bs],
+ captured_hidden_states=torch.ones((bs, 8), device=device),
+ ),
+ None,
+ )
+ drafter.runtime_states = RuntimeStates(capacity, 32, 8, device)
+ drafter.runtime_states.init_draft_trees(8)
+ spec = SimpleNamespace(
+ config=SimpleNamespace(topk=1, num_steps=7, num_nodes=8),
+ chain_parent=torch.arange(-1, 7, dtype=torch.int32, device=device),
+ draft_parent_buf=torch.zeros((capacity, 8), dtype=torch.int32, device=device),
+ )
+ policy = DevicePolicy(
+ None if scheduled else records(),
+ verify_num=8,
+ node_top_k=1,
+ tree_depth=7,
+ compute_intensity="chain_intensity",
+ is_moe_target=False,
+ exec_mode=0,
+ benchmark_config="",
+ chain_width_table=((1, 4),) if scheduled else (),
+ device=device,
+ )
+ drafter.bind_dynamic_tree(spec, policy)
+ backend = FlashInferSamplingBackend(SamplingBackendConfig(
+ synthetic_acceptance_length=None, max_bs=capacity, max_draft_tokens_per_req=8,
+ max_req_pool_size=capacity + 1, vocab_size=32, device="cuda",
+ enable_speculative_sampling=True, enable_output_logprobs=False,
+ sampling_stream="batch", logprob_order="torch",
+ ))
+ drafter.bind_sampling_backend(backend)
+ drafter.enable_sampled_trees(num_candidates=4, seed=17)
+ return drafter, backend
+
+
[email protected]("capacity", [64, 512])
[email protected]("scheduled", [False, True])
[email protected]("graphs", [False, True])
+def test_sampled_chain_rounds_after_idle_warmup(capacity, scheduled, graphs):
+ drafter, backend = _chain(capacity, scheduled)
+ rows = capacity
+ inputs = SimpleNamespace(
+ num_extends=rows,
+ accept_lengths=torch.zeros(rows, dtype=torch.int32, device="cuda"),
+ base_model_output=torch.ones(rows, dtype=torch.int32, device="cuda"),
+ )
+ drafter.prepare_round_sampling([])
+ for _ in range(3):
+ drafter.draft(inputs)
+ if graphs:
+ drafter.capture_round_graphs(
+ rows, lo_bs=0, stream=torch.cuda.Stream(), pool=None
+ )
+ decode = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(decode):
+ drafter.draft(inputs)
+ try:
+ for seq, (live, sampled) in enumerate(
+ ((3, True), (1, False), (33, True), (capacity, True)), 1
+ ):
+ params = [
+ SamplingParams(
+ temperature=1.0 if sampled and i % 2 == 0 else 0.0, seed=97 + i
+ )
+ for i in range(live)
+ ]
+ for p in params:
+ p.normalize(None)
+ slots = list(range(1, live + 1))
+ backend.prepare_step(
+ [f"{seq}-{i}" for i in slots], slots, params, num_tokens_per_req=8
+ )
+ drafter.prepare_round_sampling(params)
+ drafter.input_buffers.req_pool_indices_buf[live:].zero_()
+ drafter.input_buffers.state_write_req_pool_indices_buf[live:].zero_()
+ drafter.input_buffers.req_pool_indices_buf[:live].copy_(
+ torch.arange(1, live + 1, device="cuda")
+ )
+ drafter.input_buffers.state_write_req_pool_indices_buf[:live].copy_(
+ torch.arange(1, live + 1, device="cuda")
+ )
+ ctx = SimpleNamespace(
+ bs=live,
+ num_extends=0,
+ global_num_tokens=None,
+ global_bs=None,
+ all_decode_or_idle=True,
+ )
+ if graphs:
+ drafter.replay_decode_graph(decode, bs=live, graph_bs=rows)
+ else:
+ eager = SimpleNamespace(
+ num_extends=live,
+ accept_lengths=inputs.accept_lengths[:live],
+ base_model_output=inputs.base_model_output[:live],
+ )
+ drafter.draft(eager)
+ drafter.finish_round(ctx, rows if graphs else None)
+ drafter.complete_round()
+ torch.cuda.synchronize()
+ width = drafter.policy.verify_num.item()
+ if seq == 1:
+ assert width == (4 if scheduled else 2)
+ expected = torch.arange(-1, width - 1, dtype=torch.int32, device="cuda")
+ torch.testing.assert_close(
+ drafter.runtime_states.future_parent_map[1 : live + 1, :width],
+ expected.expand(live, width),
+ )
+ assert (
+ drafter.policy.go_ready(drafter.policy.last_depth.item() + 1, seq)
+ is False
+ )
+ if sampled:
+ assert drafter.runtime_states.future_draft_q.slot[1, 1].item() == 0
+ finally:
+ drafter.release_round_graphs()
+
+
[email protected]("scheduled", [False, True])
[email protected]("graph_phase", [False, True])
+def test_forward_runner_warmup_policy_frontier(monkeypatch, scheduled, graph_phase):
+ """Exercise real warmup buffers without loading target/draft weights."""
+ from tokenspeed.runtime.execution import forward_step
+
+ drafter, _backend = _chain(64, scheduled)
+ inputs = SimpleNamespace(
+ num_extends=0,
+ accept_lengths=torch.ones(4, dtype=torch.int32, device="cuda"),
+ base_model_output=torch.ones(
+ 4 * drafter.spec_num_tokens, dtype=torch.int32, device="cuda"
+ ),
+ )
+ observed = []
+ begin_round = drafter.policy.begin_round
+
+ def inspect_begin_round(*args):
+ signature = [(str(t.dtype), str(t.device)) for t in args]
+ observed.append(signature)
+ print("warmup policy operands (live_rows, frontier, sampled):", signature)
+ return begin_round(*args)
+
+ monkeypatch.setattr(drafter.policy, "begin_round", inspect_begin_round)
+ monkeypatch.setattr(forward_step.dist, "barrier", lambda: None)
+
+ def forward(*, bs, ctx, sampling_info):
+ assert bs == 4 and sampling_info.valid_cache_lengths is not None
+ inputs.base_ctx = ctx
+ drafter.draft(inputs)
+
+ runner = SimpleNamespace(
+ _forward_func=forward,
+ _prepare_request_token_history_graph_inputs=lambda **kwargs: None,
+ _prepare_sampling_capture=lambda **kwargs: None,
+ _init_capture_metadata=lambda bs: None,
+ attn_backend=None,
+ token_to_kv_pool=None,
+ max_tokens_per_req=drafter.spec_num_tokens,
+ drafter=drafter,
+ dp_size=1,
+ input_buffers=drafter.input_buffers,
+ runtime_states=drafter.runtime_states,
+ vocab_size=4,
+ device="cuda",
+ device_module=torch.cuda,
+ eager_grammar_buffers=None,
+ capturable_grammar=None,
+ grammar_backend=None,
+ sampling_backend=None,
+ )
+ drafter.prepare_round_sampling([])
+ forward_step.ForwardStepRunner.warmup_decode_path(
+ runner, (4,), graph_phase=graph_phase
+ )
+ device = str(torch.device("cuda", torch.cuda.current_device()))
+ assert observed == [
+ [("torch.int32", device), ("torch.int64", device), ("torch.bool", device)]
+ ]
+ assert drafter._round_seq == 0
+ assert drafter.policy._round_seq.item() == 0
diff --git a/tests/tokenspeed_round/test_sampled_tree_ops_gpu.py b/tests/tokenspeed_round/test_sampled_tree_ops_gpu.py
new file mode 100644
index 0000000..731b9bc
--- /dev/null
+++ b/tests/tokenspeed_round/test_sampled_tree_ops_gpu.py
@@ -0,0 +1,494 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Reference sampled-tree proposal and rejection kernels, including their output law."""
+
+
+import pytest
+import torch
+
+pytest.importorskip("tvm_ffi", reason="TokenSpeed round kernels require apache-tvm-ffi")
+
+from eagle_harness.tokenspeed.tree_round.ops.tree import (
+ eagle_harness_publish_draft_q,
+ eagle_harness_residual_sample,
+ eagle_harness_sample_children,
+ eagle_harness_tree_reject_sample,
+)
+
+pytestmark = pytest.mark.skipif(
+ not torch.cuda.is_available(), reason="CUDA GPU is required"
+)
+_DEVICE = "cuda"
+
+
+def _count(value: int) -> torch.Tensor:
+ """A device int32 ``[1]`` count, as the drafter's round state holds them."""
+ return torch.tensor([value], dtype=torch.int32, device=_DEVICE)
+
+
+def test_sample_children_reads_strided_rows() -> None:
+ """Each request's first R of K lane rows, read in place (and the head's
+ row-strided candidate ids), draw exactly what packed copies draw."""
+ reqs, k, expanded, nc, vocab = 3, 4, 2, 64, 300
+ gen = torch.Generator().manual_seed(7)
+ logits = (torch.randn((reqs * k, nc), generator=gen) * 2).to(_DEVICE)
+ cand = torch.randint(0, vocab + 20, (reqs * k, nc + 3), generator=gen).to(_DEVICE)
+ cand = cand[:, :nc]
+ tokens = torch.randint(0, vocab, (reqs * k, k), generator=gen).to(_DEVICE)
+ scores = torch.rand((reqs * k, k), generator=gen).to(_DEVICE)
+ # A sampling request, a greedy one, and one cut to top-k / top-p.
+ temps = torch.tensor([1.0, 0.0, 0.7], device=_DEVICE)
+ top_ks = torch.tensor([1 << 30, 1 << 30, 5], dtype=torch.int32, device=_DEVICE)
+ top_ps = torch.tensor([1.0, 1.0, 0.8], device=_DEVICE)
+
+ def lanes(rows: torch.Tensor) -> torch.Tensor:
+ return rows.view(reqs, k, -1)[:, :expanded]
+
+ def draw(*rows: torch.Tensor, width: torch.Tensor | None) -> list[torch.Tensor]:
+ tables = [
+ torch.zeros((reqs, 1 + k, nc), device=_DEVICE),
+ torch.zeros((reqs, 1 + k, nc), dtype=torch.int32, device=_DEVICE),
+ torch.full((reqs, 64), -1, dtype=torch.int32, device=_DEVICE),
+ torch.zeros((reqs, 64), dtype=torch.int32, device=_DEVICE),
+ ]
+ eagle_harness_sample_children(
+ *rows, temps, top_ks, top_ps, *tables, width, 1, _count(5), vocab, 11,
+ torch.tensor([3], device=_DEVICE), 1,
+ ) # fmt: skip
+ return tables
+
+ def full(rows: torch.Tensor) -> torch.Tensor:
+ return rows.view(reqs, k, -1)
+
+ # All K lanes passed with the expanded width on the device draw what the
+ # expanded lanes alone draw.
+ packed = [lanes(rows).contiguous() for rows in (logits, cand, tokens, scores)]
+ packed_tables = draw(*packed, width=None)
+ in_place = tokens.clone(), scores.clone()
+ tables = draw(
+ full(logits), full(cand), *map(full, in_place), width=_count(expanded)
+ )
+ assert (packed_tables[2][0] >= 0).any() and (packed_tables[2][1] == -1).all()
+ for actual, expected in zip(
+ [*map(lanes, in_place), *tables], packed[2:] + packed_tables
+ ):
+ assert torch.equal(actual, expected)
+ # The lanes past the expanded ones keep their children.
+ for actual, before in zip(in_place, (tokens, scores)):
+ assert torch.equal(
+ actual.view(reqs, k, k)[:, expanded:], before.view(reqs, k, k)[:, expanded:]
+ )
+
+
+def test_sampled_proposals_advance_on_graph_replay():
+ """A replay advances the device RNG counter; resetting it repeats the draw."""
+ bs, nc, k = 8, 64, 4
+ logits = torch.zeros((bs, 1, nc), device=_DEVICE)
+ ids = torch.arange(nc, device=_DEVICE).view(1, 1, nc).repeat(bs, 1, 1)
+ tokens = torch.zeros((bs, 1, k), dtype=torch.int64, device=_DEVICE)
+ scores = torch.ones((bs, 1, k), device=_DEVICE)
+ temps = torch.ones(bs, device=_DEVICE)
+ top_ks, top_ps = _no_top_k(bs), torch.ones(bs, device=_DEVICE)
+ q = torch.zeros((bs, 1, nc), device=_DEVICE)
+ q_ids = torch.zeros_like(q, dtype=torch.int32)
+ slot = torch.full((bs, k + 1), -1, dtype=torch.int32, device=_DEVICE)
+ pos = torch.zeros_like(slot)
+ counter, start = torch.zeros(1, dtype=torch.int64, device=_DEVICE), _count(1)
+
+ def draw():
+ counter.add_(1)
+ eagle_harness_sample_children(
+ logits, ids, tokens, scores, temps, top_ks, top_ps, q, q_ids,
+ slot, pos, None, 0, start, nc, 31, counter, 0,
+ ) # fmt: skip
+
+ stream = torch.cuda.Stream()
+ stream.wait_stream(torch.cuda.current_stream())
+ with torch.cuda.stream(stream):
+ draw()
+ torch.cuda.current_stream().wait_stream(stream)
+ graph = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(graph, stream=stream):
+ draw()
+ counter.zero_()
+ graph.replay()
+ first = tokens.clone()
+ graph.replay()
+ second = tokens.clone()
+ assert counter.item() == 2
+ assert not torch.equal(first, second)
+ counter.zero_()
+ graph.replay()
+ assert torch.equal(tokens, first)
+ assert (slot[:, 0] == -1).all()
+ assert (slot[:, 1:] == 0).all()
+ torch.testing.assert_close(q, torch.full_like(q, 1 / nc), rtol=0, atol=0)
+
+
+def _sampled_round(target_rows, draft_logits, cand, topk, generator):
+ """One round per request at temperature 1: sample the root's K children
+ (and each child's K grandchildren) from the draft, accept by rejection,
+ draw the bonus; returns each request's emitted tokens (-1 past them).
+
+ target_rows: ``[1 + K + K * K, V]`` the target's distribution at every node
+ (root, children, grandchildren in pool order); draft_logits / cand:
+ ``[1 + K, NC]`` the draft's logits over candidate ids at the root and at
+ each child."""
+ # The children kernel keys at most 1024 rows per launch: 256 requests x 3 children.
+ reqs, nc = 256, cand.shape[1]
+ k, vocab = topk, target_rows.shape[1]
+ max_nodes, slots = 64, 1 + k
+ nodes = 1 + k + k * k
+ dev = "cuda"
+ temps = torch.ones(reqs, device=dev)
+ top_ks = _no_top_k(reqs)
+ top_ps = torch.ones(reqs, device=dev)
+ q_store = torch.zeros((reqs, slots, nc), device=dev)
+ qid_store = torch.zeros((reqs, slots, nc), dtype=torch.int32, device=dev)
+ node_slot = torch.full((reqs, max_nodes), -1, dtype=torch.int32, device=dev)
+ node_pos = torch.zeros((reqs, max_nodes), dtype=torch.int32, device=dev)
+ counter = torch.randint(0, 1 << 30, (1,), generator=generator).to(dev)
+ seed = int(torch.randint(0, 1 << 40, (1,), generator=generator))
+ # Depth 1: the root's children; depth 2: each child's children.
+ root_tokens = cand[0, :k].repeat(reqs, 1).contiguous()
+ eagle_harness_sample_children(
+ draft_logits[:1].repeat(reqs, 1)[:, None], cand[:1].repeat(reqs, 1)[:, None],
+ root_tokens[:, None], torch.zeros((reqs, 1, k), device=dev), temps, top_ks, top_ps,
+ q_store, qid_store, node_slot, node_pos, None, 0, _count(1), vocab, seed, counter,
+ 0,
+ ) # fmt: skip
+ # A child's draft row is its own (indexed by the child's rank among the root's).
+ child_logits = draft_logits[1:].repeat(reqs, 1).contiguous()
+ child_cand = cand[1:].repeat(reqs, 1).contiguous()
+ grand_tokens = child_cand[:, :k].contiguous()
+ eagle_harness_sample_children(
+ child_logits.view(reqs, k, -1), child_cand.view(reqs, k, -1),
+ grand_tokens.view(reqs, k, k), torch.zeros((reqs, k, k), device=dev),
+ temps, top_ks, top_ps, q_store, qid_store, node_slot, node_pos,
+ None, 1, _count(1 + k), vocab, seed, counter, 1,
+ ) # fmt: skip
+ tokens = torch.cat(
+ [torch.zeros((reqs, 1), dtype=torch.int64, device=dev), root_tokens,
+ grand_tokens.view(reqs, k * k)], dim=1,
+ ).to(torch.int32) # fmt: skip
+ parents = torch.tensor(
+ [-1] + [0] * k + [1 + c for c in range(k) for _ in range(k)],
+ dtype=torch.int32,
+ device=dev,
+ ).repeat(reqs, 1)
+ rows = torch.arange(reqs, device=dev)
+ probas = target_rows.repeat(reqs, 1).contiguous()
+ argmax = probas.argmax(dim=-1)
+ q_tab = torch.zeros_like(q_store)
+ qid_tab = torch.zeros_like(qid_store)
+ slot_tab = torch.zeros((reqs, nodes), dtype=torch.int32, device=dev)
+ pos_tab = torch.zeros_like(slot_tab)
+ ranked = torch.arange(nodes, device=dev).repeat(reqs, 1)
+ eagle_harness_publish_draft_q(
+ ranked, node_slot, node_pos, q_store, qid_store, rows, q_tab, qid_tab,
+ slot_tab, pos_tab, _count(reqs), _count(nodes),
+ ) # fmt: skip
+ # Every sampled node's published (slot, position) names its own candidate.
+ sampled = slot_tab >= 0
+ req = torch.arange(reqs, device=dev)[:, None].expand(-1, nodes)
+ named = qid_tab[req, slot_tab.clamp(min=0).long(), pos_tab.long()]
+ assert torch.equal(named[sampled], tokens[sampled])
+ coins = torch.rand((reqs, nodes), generator=generator).to(dev)
+ final_coins = torch.rand(reqs, generator=generator).to(dev)
+ path, predicts, accept_length, _ = _verify(
+ probas, tokens, parents, rows, (slot_tab, pos_tab, q_tab, qid_tab), coins,
+ final_coins, _no_top_k(reqs * nodes), argmax,
+ ) # fmt: skip
+ emitted = predicts[:, :3].cpu()
+ length = accept_length.cpu()
+ emitted[torch.arange(3)[None, :] >= length[:, None]] = -1
+ return emitted, path.cpu()
+
+
+def test_sampled_tree_emits_the_target_distribution() -> None:
+ """Children drawn from the draft, recursive rejection and the residual bonus
+ together emit exactly the target: the first token's law is the root's
+ target, the second's (after an accepted child) that child's."""
+ topk, vocab, nc = 3, 48, 32
+ generator = torch.Generator().manual_seed(0)
+ target = torch.softmax(
+ torch.randn((1 + topk + topk * topk, vocab), generator=generator) * 1.5, dim=-1
+ ).cuda()
+ cand = torch.stack(
+ [torch.randperm(vocab, generator=generator)[:nc] for _ in range(1 + topk)]
+ ).cuda()
+ draft_logits = (torch.randn((1 + topk, nc), generator=generator) * 1.5).cuda()
+ first = torch.zeros(vocab)
+ second = torch.zeros((topk, vocab))
+ trials = 240
+ for _ in range(trials):
+ emitted, path = _sampled_round(target, draft_logits, cand, topk, generator)
+ first += torch.bincount(emitted[:, 0], minlength=vocab).float()
+ # Rows whose first token is an accepted child (node path[1]) and that emitted a second.
+ child = path[:, 1].long() - 1
+ has_second = (child >= 0) & (emitted[:, 1] >= 0)
+ for c in range(topk):
+ rows = has_second & (child == c)
+ second[c] += torch.bincount(emitted[rows, 1], minlength=vocab).float()
+ total = trials * 256
+ torch.testing.assert_close(first / total, target[0].cpu(), rtol=0, atol=0.01)
+ for c in range(topk):
+ if second[c].sum() > 3000:
+ torch.testing.assert_close(
+ second[c] / second[c].sum(), target[1 + c].cpu(), rtol=0, atol=0.02
+ )
+
+
+def _no_top_k(rows: int) -> torch.Tensor:
+ """Per-row top-k of sampled (never greedy) rows."""
+ return torch.full((rows,), 1 << 30, dtype=torch.int32, device=_DEVICE)
+
+
+def _two_node_tree(bs: int, child_token: int, q: torch.Tensor):
+ """A root (token 7) and one child whose q (slot 0) is ``q`` over candidate
+ ids 0..NC-1: tokens, parents and the q tables (slot, pos, q, ids)."""
+ nc = q.numel()
+ tokens = torch.tensor([7, child_token], dtype=torch.int32, device=_DEVICE).repeat(
+ bs, 1
+ )
+ parents = torch.tensor([-1, 0], dtype=torch.int32, device=_DEVICE).repeat(bs, 1)
+ q_tab = q.view(1, 1, nc).repeat(bs, 1, 1).contiguous()
+ qid_tab = (
+ torch.arange(nc, dtype=torch.int32, device=_DEVICE)
+ .view(1, 1, nc)
+ .repeat(bs, 1, 1)
+ )
+ slot_tab = torch.tensor([-1, 0], dtype=torch.int32, device=_DEVICE).repeat(bs, 1)
+ pos_tab = torch.tensor([0, child_token], dtype=torch.int32, device=_DEVICE).repeat(
+ bs, 1
+ )
+ return tokens, parents, (slot_tab, pos_tab, q_tab, qid_tab)
+
+
+def _verify(
+ probas, tokens, parents, q_rows, q_tables, coins, final_coins, top_ks, argmax
+):
+ """Rejection-sample each request's tree, then draw its bonus: path,
+ predicts (``[bs, N]``), accept length and last row."""
+ bs, n = tokens.shape
+ path = torch.empty((bs, n), dtype=torch.int32, device=_DEVICE)
+ predicts = torch.full((bs * n,), -1, dtype=torch.int32, device=_DEVICE)
+ accept_length = torch.empty(bs, dtype=torch.int32, device=_DEVICE)
+ last_row = torch.empty(bs, dtype=torch.int64, device=_DEVICE)
+ eagle_harness_tree_reject_sample(
+ probas, tokens, parents, q_rows, *q_tables, coins, top_ks, argmax, path,
+ predicts, accept_length, last_row,
+ ) # fmt: skip
+ eagle_harness_residual_sample(
+ probas, last_row, final_coins, top_ks, argmax, accept_length, predicts, n
+ )
+ return path, predicts.view(bs, n), accept_length, last_row
+
+
+def _verify_sampled(probas, tokens, parents, q_tables, coins, final_coins):
+ """``_verify`` of sampled rows, q tables at the requests' own rows; the
+ argmax is the kernels' own, read from probas."""
+ bs, n = tokens.shape
+ unread = torch.full((bs * n,), -1, dtype=torch.int64, device=_DEVICE)
+ _, predicts, accept_length, _ = _verify(
+ probas, tokens, parents, torch.arange(bs, device=_DEVICE), q_tables, coins,
+ final_coins, _no_top_k(bs * n), unread,
+ ) # fmt: skip
+ return predicts, accept_length
+
+
+def _sample_root_children(logits, cand, tokens, *, top_k, top_p, vocab, seed):
+ """Redraw each request's ``[bs, K]`` root children in place from its
+ ``[bs, NC]`` draft logits over ``cand`` at temperature 1; returns the q
+ tables (store, ids, node slots, node positions)."""
+ bs, nc = logits.shape
+ k = tokens.shape[1]
+ tables = (
+ torch.zeros((bs, 1, nc), device=_DEVICE),
+ torch.zeros((bs, 1, nc), dtype=torch.int32, device=_DEVICE),
+ torch.full((bs, 8), -1, dtype=torch.int32, device=_DEVICE),
+ torch.zeros((bs, 8), dtype=torch.int32, device=_DEVICE),
+ )
+ eagle_harness_sample_children(
+ logits[:, None], cand[:, None], tokens[:, None],
+ torch.zeros((bs, 1, k), device=_DEVICE), torch.ones(bs, device=_DEVICE),
+ torch.full((bs,), top_k, dtype=torch.int32, device=_DEVICE),
+ torch.full((bs,), top_p, device=_DEVICE), *tables, None, 0, _count(1), vocab,
+ seed, torch.zeros(1, dtype=torch.int64, device=_DEVICE), 0,
+ ) # fmt: skip
+ return tables
+
+
+def test_exhausted_residual_never_emits_a_zero_probability_child() -> None:
+ """q puts 3e-8 on the drawn child and the rest on the target's one-hot
+ token: the child (p = 0) is always rejected and the bonus is the target's."""
+ bs, vocab, nc = 64, 300, 16
+ q = torch.zeros(nc, device=_DEVICE)
+ q[5], q[9] = 1.0, 3.07e-8
+ tree = _two_node_tree(bs, 9, q)
+ probas = torch.zeros((bs * 2, vocab), device=_DEVICE)
+ probas[:, 5] = 1.0
+ coins = torch.rand((bs, 2), device=_DEVICE)
+ predicts, accept_length = _verify_sampled(
+ probas, *tree, coins, torch.rand(bs, device=_DEVICE)
+ )
+ assert (accept_length == 1).all() and (predicts[:, 0] == 5).all()
+
+
+def test_exhausted_residual_accepts_the_target_argmax() -> None:
+ """q one-hot on the target's one-hot token (a logit gap past fp32 exp): the
+ drawn child is accepted for every coin, even one just below 1."""
+ bs, vocab, nc, k = 64, 300, 16, 3
+ logits = torch.full((bs, nc), -200.0, device=_DEVICE)
+ logits[:, 5] = 0.0
+ cand = torch.arange(nc, device=_DEVICE).repeat(bs, 1).contiguous()
+ tokens = cand[:, :k].contiguous()
+ q_store, qid_store, node_slot, node_pos = _sample_root_children(
+ logits, cand, tokens, top_k=1 << 30, top_p=1.0, vocab=vocab, seed=3
+ )
+ assert (tokens[:, 0] == 5).all()
+ tree = (
+ torch.stack([torch.full((bs,), 7, device=_DEVICE), tokens[:, 0]], 1).to(torch.int32),
+ torch.tensor([-1, 0], dtype=torch.int32, device=_DEVICE).repeat(bs, 1),
+ (
+ torch.stack([torch.full((bs,), -1, device=_DEVICE), node_slot[:, 1]], 1).to(torch.int32),
+ torch.stack([torch.zeros(bs, device=_DEVICE), node_pos[:, 1]], 1).to(torch.int32),
+ q_store, qid_store,
+ ),
+ ) # fmt: skip
+ probas = torch.zeros((bs * 2, vocab), device=_DEVICE)
+ probas[:, 5] = 1.0
+ coins = torch.full((bs, 2), 1.0 - 2**-24, device=_DEVICE)
+ predicts, accept_length = _verify_sampled(
+ probas, *tree, coins, torch.rand(bs, device=_DEVICE)
+ )
+ assert (accept_length == 2).all() and (predicts[:, 0] == 5).all()
+
+
[email protected]("top_k,top_p", [(3, 1.0), (1 << 30, 0.5)])
+def test_sampled_children_respect_top_k_and_top_p(top_k: int, top_p: float) -> None:
+ """A request draws only from the draft's ``top_k`` best candidates and,
+ with top-p, from the smallest prefix (by q) holding that mass."""
+ bs, vocab, nc, k = 256, 300, 16, 2
+ gen = torch.Generator().manual_seed(4)
+ logits = (
+ (torch.randn((1, nc), generator=gen) * 2).to(_DEVICE).repeat(bs, 1).contiguous()
+ )
+ cand = (
+ torch.randperm(vocab, generator=gen)[:nc].to(_DEVICE).repeat(bs, 1).contiguous()
+ )
+ probs = torch.softmax(logits[0], -1)
+ order = torch.argsort(probs, descending=True)
+ keep = min(top_k, int((torch.cumsum(probs[order], 0) < top_p).sum()) + 1)
+ allowed = set(cand[0, order[:keep]].tolist())
+ tokens = cand[:, :k].contiguous()
+ _sample_root_children(
+ logits, cand, tokens, top_k=top_k, top_p=top_p, vocab=vocab, seed=5
+ )
+ first = set(tokens[:, 0].tolist())
+ assert first <= allowed and len(first) > 1
+
+
+def test_publish_marks_slots_past_the_verify_width_deterministic() -> None:
+ bs, nodes, nc = 4, 8, 16
+ ranked = torch.arange(nodes, device=_DEVICE).repeat(bs, 1)
+ node_slot = torch.zeros((bs, 64), dtype=torch.int32, device=_DEVICE)
+ node_pos = torch.ones_like(node_slot)
+ q_store = torch.rand((bs, 3, nc), device=_DEVICE)
+ qid_store = torch.randint(0, 100, (bs, 3, nc), dtype=torch.int32, device=_DEVICE)
+ slot_tab = torch.full((bs + 1, nodes), 7, dtype=torch.int32, device=_DEVICE)
+ pos_tab = torch.zeros_like(slot_tab)
+ q_tab = torch.zeros((bs + 1, 3, nc), device=_DEVICE)
+ qid_tab = torch.zeros((bs + 1, 3, nc), dtype=torch.int32, device=_DEVICE)
+ rows = torch.arange(1, bs + 1, device=_DEVICE)
+ eagle_harness_publish_draft_q(
+ ranked, node_slot, node_pos, q_store, qid_store, rows, q_tab, qid_tab,
+ slot_tab, pos_tab, _count(bs), _count(5),
+ ) # fmt: skip
+ assert (slot_tab[1:, 0] == -1).all() # the root
+ assert (slot_tab[1:, 1:5] == 0).all()
+ assert (slot_tab[1:, 5:] == -1).all() # past the verify width
+ torch.testing.assert_close(q_tab[1:], q_store, rtol=0, atol=0)
+
+
+def test_publish_respects_request_permutation_and_padding():
+ bs, nodes, nc = 4, 5, 8
+ ranked = torch.tensor([0, 3, 1, 4, 2], device=_DEVICE).repeat(bs, 1)
+ slot = torch.tensor([-1, 1, 1, 0, 0], dtype=torch.int32, device=_DEVICE).repeat(
+ bs, 1
+ )
+ pos = torch.arange(nodes, dtype=torch.int32, device=_DEVICE).repeat(bs, 1)
+ q = torch.arange(bs * 2 * nc, dtype=torch.float32, device=_DEVICE).view(bs, 2, nc)
+ q_ids = q.to(torch.int32)
+ rows = torch.tensor([3, 1, 4, 0], device=_DEVICE)
+ q_tab = torch.full((6, 2, nc), -2.0, device=_DEVICE)
+ qid_tab = torch.full((6, 2, nc), -2, dtype=torch.int32, device=_DEVICE)
+ slot_tab = torch.full((6, nodes), -2, dtype=torch.int32, device=_DEVICE)
+ pos_tab = torch.full_like(slot_tab, -2)
+ eagle_harness_publish_draft_q(
+ ranked, slot, pos, q, q_ids, rows, q_tab, qid_tab, slot_tab, pos_tab,
+ _count(3), _count(4),
+ ) # fmt: skip
+ for batch, request in enumerate([3, 1, 4]):
+ assert torch.equal(q_tab[request], q[batch])
+ assert torch.equal(qid_tab[request], q_ids[batch])
+ assert slot_tab[request].tolist() == [-1, 0, 1, 0, -1]
+ assert pos_tab[request].tolist() == [0, 3, 1, 4, 0]
+ for untouched in [0, 2, 5]:
+ assert (q_tab[untouched] == -2).all()
+ assert (slot_tab[untouched] == -2).all()
+
+
+def test_vanished_residual_takes_the_rows_first_argmax() -> None:
+ """A sampled row whose residual vanishes takes torch.argmax of its target
+ row as the bonus, although the rejection already lowered that entry: the
+ drawn child (p = 0) is rejected, and q equal to p on the other candidates
+ leaves no residual. The target ties at tokens 50 and 20 (q position 0 and
+ 1): the lower token wins."""
+ bs, vocab, nc = 64, 300, 16
+ ids = torch.arange(nc, dtype=torch.int32, device=_DEVICE)
+ ids[:4] = torch.tensor([50, 20, 80, 9], dtype=torch.int32)
+ q = torch.zeros(nc, device=_DEVICE)
+ q[:4] = torch.tensor([0.375, 0.375, 0.25 - 3.0e-8, 3.0e-8])
+ tokens, parents, q_tables = _two_node_tree(bs, 9, q)
+ _, pos_tab, _, qid_tab = q_tables
+ qid_tab[:] = ids
+ pos_tab[:, 1] = 3
+ probas = torch.zeros((bs * 2, vocab), device=_DEVICE)
+ probas[:, [50, 20, 80]] = torch.tensor([0.375, 0.375, 0.25], device=_DEVICE)
+ coins = torch.rand((bs, 2), device=_DEVICE)
+ # Final coins below 0.99: the bonus row's 3e-8 residual left on token 80 is never drawn.
+ predicts, accept_length = _verify_sampled(
+ probas, tokens, parents, q_tables, coins, torch.rand(bs, device=_DEVICE) * 0.99
+ )
+ assert (accept_length == 1).all() and (predicts[:, 0] == 20).all()
+ # The root's row: its argmax set to 1 over the vanished residual.
+ assert (probas[0::2, 20] == 1.0).all() and (probas[0::2, 50] < 1e-6).all()
+
+
[email protected]("vocab", [151936, 40001])
+def test_residual_bonus_inverts_the_cdf_of_a_wide_row(vocab: int) -> None:
+ """Wide rows stage each thread's segment in several runs: the bonus is the
+ token whose CDF interval holds the coin (aimed at interval middles, clear
+ of rounding), over an unnormalized row."""
+ bs, n, positive = 16, 4, 64
+ gen = torch.Generator().manual_seed(vocab)
+ probas = torch.zeros((bs * n, vocab))
+ idx = torch.stack(
+ [torch.randperm(vocab, generator=gen)[:positive] for _ in range(bs * n)]
+ )
+ probas.scatter_(1, idx, torch.rand((bs * n, positive), generator=gen) + 0.5)
+ last_row = torch.arange(bs) * n + torch.randint(0, n, (bs,), generator=gen)
+ expected = idx[last_row, torch.randint(0, positive, (bs,), generator=gen)]
+ rows = probas[last_row].double()
+ mass = rows.gather(1, expected[:, None]).squeeze(1)
+ below = rows.cumsum(-1).gather(1, expected[:, None]).squeeze(1) - mass
+ coins = ((below + 0.5 * mass) / rows.sum(-1)).float()
+ predicts = torch.full((bs * n,), -1, dtype=torch.int32, device=_DEVICE)
+ eagle_harness_residual_sample(
+ probas.to(_DEVICE), last_row.to(_DEVICE), coins.to(_DEVICE),
+ _no_top_k(bs * n), torch.full((bs * n,), -1, dtype=torch.int64, device=_DEVICE),
+ torch.full((bs,), n, dtype=torch.int32, device=_DEVICE), predicts, n,
+ ) # fmt: skip
+ assert torch.equal(predicts.view(bs, n)[:, -1].cpu().long(), expected)
diff --git a/tests/tokenspeed_round/test_tgv_device_graph.py b/tests/tokenspeed_round/test_tgv_device_graph.py
new file mode 100644
index 0000000..867d1a3
--- /dev/null
+++ b/tests/tokenspeed_round/test_tgv_device_graph.py
@@ -0,0 +1,71 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Small BF16 projections captured in a device-launched draft graph."""
+
+
+import pytest
+import torch
+
+pytest.importorskip("tvm_ffi", reason="TokenSpeed round kernels require apache-tvm-ffi")
+
+if not torch.cuda.is_available():
+ pytest.skip("needs CUDA", allow_module_level=True)
+
+pytest.importorskip("tokenspeed_kernel", reason="requires the optional TokenSpeed kernels")
+
+from tokenspeed_kernel.ops.gemm import flashinfer as gemm_flashinfer
+
+if not hasattr(gemm_flashinfer, "has_flashinfer_cute_dsl_bf16"):
+ pytest.skip("engine has no optional TGV BF16 backend", allow_module_level=True)
+
+from tokenspeed_kernel.ops.gemm.flashinfer import (
+ flashinfer_bf16_gemm,
+ has_flashinfer_cute_dsl_bf16,
+)
+
+from eagle_harness.tokenspeed.tree_round.chain import DeviceChain
+
+pytestmark = pytest.mark.skipif(
+ not torch.cuda.is_available() or not has_flashinfer_cute_dsl_bf16(),
+ reason="TGV needs CuTe DSL on SM100/SM103",
+)
+
+
[email protected]("m,k", [(1, 1024), (7, 2048), (16, 5120)])
+def test_small_bf16_gemm_replays_in_a_device_launched_child(m, k):
+ device = torch.device("cuda")
+ gen = torch.Generator(device=device).manual_seed(53)
+ x = torch.randn(m, k, device=device, generator=gen).bfloat16()
+ weight = (torch.randn(5120, k, device=device, generator=gen) * 0.05).bfloat16()
+ out = torch.empty(m, 5120, dtype=x.dtype, device=device)
+ observed = torch.empty_like(out)
+ go = torch.ones(3, dtype=torch.int32, device=device)
+ sampled = torch.zeros(1, dtype=torch.bool, device=device)
+ chain = DeviceChain(1, 2, device)
+ stream = torch.cuda.Stream()
+ flashinfer_bf16_gemm(x, weight, out)
+ torch.cuda.synchronize()
+ first = torch.cuda.CUDAGraph()
+ child = torch.cuda.CUDAGraph(keep_graph=True)
+ final = torch.cuda.CUDAGraph(keep_graph=True)
+ try:
+ with torch.cuda.graph(first, stream=stream):
+ chain.end_depth(1, 1, go, sampled)
+ with torch.cuda.graph(child, stream=stream):
+ flashinfer_bf16_gemm(x, weight, out)
+ chain.end_depth(1, 2, go, sampled)
+ with torch.cuda.graph(final, stream=stream):
+ observed.copy_(out)
+ chain.instantiate(1, [child], [final], stream)
+ stream.synchronize()
+ for _ in range(4):
+ x.copy_(torch.randn(m, k, device=device, generator=gen).bfloat16())
+ expected = (x.double() @ weight.double().T).bfloat16()
+ out.fill_(float("nan"))
+ observed.fill_(float("nan"))
+ first.replay()
+ torch.testing.assert_close(observed, expected, rtol=1e-2, atol=2e-3)
+ finally:
+ torch.cuda.synchronize()
+ chain.release()
diff --git a/tests/tokenspeed_round/test_tree_ops_gpu.py b/tests/tokenspeed_round/test_tree_ops_gpu.py
new file mode 100644
index 0000000..44145d1
--- /dev/null
+++ b/tests/tokenspeed_round/test_tree_ops_gpu.py
@@ -0,0 +1,445 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""EAGLE-Harness draft-tree kernels against PyTorch references."""
+
+import sys
+
+import numpy as np
+import pytest
+import torch
+
+pytest.importorskip("tvm_ffi", reason="TokenSpeed round kernels require apache-tvm-ffi")
+
+from eagle_harness.tokenspeed.tree_round.ops.tree import (
+ eagle_harness_draft_depth_update,
+ eagle_harness_stable_topk_desc,
+ eagle_harness_update_node_data,
+ eagle_harness_work_deltas,
+ eagle_harness_write_verify_tree,
+)
+
+pytestmark = pytest.mark.skipif(
+ not torch.cuda.is_available(), reason="CUDA GPU is required"
+)
+
+_DEVICE = "cuda"
+
+
[email protected]("k", [2, 4, 8])
+def test_update_root_children(k):
+ bs, columns = 3, 65
+ generator = torch.Generator().manual_seed(k)
+ scores = torch.rand((bs, k), generator=generator).to(_DEVICE)
+ tokens = torch.randint(0, 1000, (bs, k), generator=generator).to(_DEVICE)
+ # Row strides may differ between the pool and the work/sort lists.
+ pool_scores = torch.full((bs, columns), -1.0, device=_DEVICE)
+ pool_tokens = torch.full((bs, columns), -1, dtype=torch.int64, device=_DEVICE)
+ work = torch.full((bs, 64 + k), -1.0, device=_DEVICE)
+ sort = torch.full((bs, 64), -1.0, device=_DEVICE)
+ eagle_harness_update_node_data(pool_scores, pool_tokens, work, sort, scores, tokens)
+ for target in (pool_scores, work, sort):
+ assert torch.equal(target[:, 1 : k + 1], scores)
+ assert (target[:, 0] == -1).all()
+ assert (target[:, k + 1 :] == -1).all()
+ assert torch.equal(pool_tokens[:, 1 : k + 1], tokens)
+
+
+def _count(value: int) -> torch.Tensor:
+ """A device int32 ``[1]`` count, as the drafter's round state holds them."""
+ return torch.tensor([value], dtype=torch.int32, device=_DEVICE)
+
+
+def _distinct_scores(rows: int, cols: int, generator: torch.Generator) -> torch.Tensor:
+ """Scores in (0, 1) whose values and products almost surely never tie."""
+ return (torch.rand((rows, cols), generator=generator) * 0.98 + 0.01).to(_DEVICE)
+
+
[email protected]("n,k", [(5, 5), (1024, 64)])
+def test_stable_topk_desc(n: int, k: int) -> None:
+ generator = torch.Generator().manual_seed(n)
+ # Few distinct values: ties must keep the lower index first. A padded row
+ # and columns past n (as in a captured graph) are never read or written.
+ cols = min(n + 3, 1024)
+ scores = (torch.randint(0, 8, (4, cols), generator=generator).float() / 8).to(
+ _DEVICE
+ )
+ values = torch.full((4, k + 2), -1.0, device=_DEVICE)
+ indices = torch.full((4, k + 2), -1, dtype=torch.int64, device=_DEVICE)
+ eagle_harness_stable_topk_desc(
+ scores, _count(3), _count(n), _count(k), values, indices
+ )
+ expected = torch.sort(scores[:3, :n], dim=-1, descending=True, stable=True)
+ torch.testing.assert_close(values[:3, :k], expected.values[:, :k], rtol=0, atol=0)
+ torch.testing.assert_close(indices[:3, :k], expected.indices[:, :k], rtol=0, atol=0)
+ assert (values[3] == -1).all() and (values[:, k:] == -1).all()
+
+
[email protected]("node_count,verify_num", [(1, 16), (7, 16), (14, 16)])
+def test_work_deltas(node_count: int, verify_num: int) -> None:
+ bs, topk = 3, 4
+ generator = torch.Generator().manual_seed(node_count)
+ # One padded row past the live ones, as in a captured graph.
+ work = torch.ones((bs + 1, verify_num + topk), device=_DEVICE)
+ work[:bs] = 0.0
+ work[:bs, :node_count] = (
+ _distinct_scores(bs, node_count, generator).sort(dim=-1, descending=True).values
+ )
+ work[:bs, node_count : node_count + topk] = (
+ _distinct_scores(bs, topk, generator).sort(dim=-1, descending=True).values
+ )
+ deltas = torch.empty(topk + 1, device=_DEVICE)
+ live_rows = torch.tensor([bs], dtype=torch.int32, device=_DEVICE)
+ counts = _count(node_count), _count(verify_num)
+ eagle_harness_work_deltas(work, deltas, live_rows, counts[0], topk, counts[1])
+ unpadded = torch.empty(topk + 1, device=_DEVICE)
+ eagle_harness_work_deltas(
+ work[:bs], unpadded, live_rows, counts[0], topk, counts[1]
+ )
+ # A zero node count queues no deltas.
+ untouched = torch.full((topk + 1,), -1.0, device=_DEVICE)
+ eagle_harness_work_deltas(work, untouched, live_rows, _count(0), topk, counts[1])
+ eagle_harness_work_deltas(work, untouched, _count(0), counts[0], topk, counts[1])
+
+ assert torch.equal(deltas, unpadded) and (untouched == -1).all()
+ expected = []
+ for j in range(topk + 1):
+ merged = work[:bs, : node_count + j].sort(dim=-1, descending=True).values
+ expected.append(merged[:, : min(node_count + j, verify_num)].sum(-1).mean())
+ torch.testing.assert_close(deltas, torch.stack(expected), rtol=1e-6, atol=1e-6)
+
+
+def _work_deltas_reference(
+ work: np.ndarray, bs: int, node_count: int, verify_num: int, topk: int, rows: int
+) -> np.ndarray:
+ """The work deltas in the kernel's float32 order: each row's merge summed
+ in turn, then a halving tree over 256 threads, or 512 above 256 rows,
+ whose padded rows hold zeros."""
+ threads = 256 if rows <= 256 else 512
+ out = np.zeros(topk + 1, dtype=np.float32)
+ for j in range(topk + 1):
+ sums = np.zeros(threads, dtype=np.float32)
+ for row in range(bs):
+ head, tail = work[row, :node_count], work[row, node_count:]
+ a = b = 0
+ total = np.float32(0.0)
+ for _ in range(min(node_count + j, verify_num)):
+ va = head[a] if a < node_count else np.float32(0.0)
+ vb = tail[b] if b < j else np.float32(0.0)
+ if va >= vb:
+ total, a = np.float32(total + va), a + 1
+ else:
+ total, b = np.float32(total + vb), b + 1
+ sums[row] = total
+ half = threads // 2
+ while half:
+ sums[:half] = sums[:half] + sums[half : 2 * half]
+ half //= 2
+ out[j] = np.float32(sums[0] / np.float32(bs))
+ return out
+
+
+ "bs,rows",
+ [(1, 1), (3, 4), (16, 32), (31, 32), (32, 32)],
+)
+def test_work_deltas_sum_order(bs: int, rows: int) -> None:
+ """Bit for bit the kernel's summation order up to 512 rows (padded rows
+ past the live ones, as in a captured graph); up to 256 live rows the
+ 256- and 512-thread halving trees give the same bits."""
+ node_count, verify_num, topk = 7, 16, 4
+ generator = torch.Generator().manual_seed(bs)
+ work = torch.zeros((rows, verify_num + topk))
+ work[:bs, :node_count] = _distinct_scores(bs, node_count, generator).cpu()
+ work[:bs, :node_count] = work[:bs, :node_count].sort(-1, descending=True).values
+ tail = _distinct_scores(bs, topk, generator).cpu().sort(-1, descending=True).values
+ work[:bs, node_count : node_count + topk] = tail
+ work[bs:] = 1.0
+ deltas = torch.empty(topk + 1, device=_DEVICE)
+ eagle_harness_work_deltas(
+ work.to(_DEVICE),
+ deltas,
+ _count(bs),
+ _count(node_count),
+ topk,
+ _count(verify_num),
+ )
+ expected = _work_deltas_reference(
+ work.numpy(), bs, node_count, verify_num, topk, rows
+ )
+ assert np.array_equal(deltas.cpu().numpy(), expected)
+ if bs <= 256:
+ other = _work_deltas_reference(
+ work.numpy(), bs, node_count, verify_num, topk, 512 if rows <= 256 else 256
+ )
+ assert np.array_equal(other, expected)
+
+
+def _bitonic_sort_64(scores: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ """The kernels' descending sort of each row's ``n <= 64`` scores: a
+ bitonic network over 64 positions that skips every pair reaching past
+ ``n`` and never swaps ties, so its order (not always fully sorted when
+ ``n`` is not a power of two) is a fixed function of the inputs. Returns
+ the values and their original positions."""
+ rows, n = scores.shape
+ values = scores.clone()
+ order = torch.arange(n, device=scores.device).repeat(rows, 1)
+ size = 2
+ while size <= 64:
+ stride = size // 2
+ while stride:
+ lower = [p for p in range(64) if not p & stride and p + stride < n]
+ if lower:
+ i = torch.tensor(lower, device=scores.device)
+ j = i + stride
+ vi, vj, oi, oj = values[:, i], values[:, j], order[:, i], order[:, j]
+ swap = torch.where((i & size) == 0, vi < vj, vi > vj)
+ values[:, i] = torch.where(swap, vj, vi)
+ values[:, j] = torch.where(swap, vi, vj)
+ order[:, i] = torch.where(swap, oj, oi)
+ order[:, j] = torch.where(swap, oi, oj)
+ stride //= 2
+ size *= 2
+ return values, order
+
+
+def _lane_mask_words(mask: torch.Tensor, lane_mask: torch.Tensor) -> None:
+ """Bool ``[rows, K, window]`` lane masks as int64 words: window slot ``j``
+ at bit ``j % 64`` of word ``j // 64``, later words zero."""
+ window = mask.shape[-1]
+ bits = 1 << (torch.arange(window, device=mask.device) % 64)
+ for word in range(lane_mask.shape[-1]):
+ lo, hi = 64 * word, min(64 * word + 64, window)
+ if lo >= hi:
+ lane_mask[..., word].zero_()
+ continue
+ torch.sum(mask[..., lo:hi] * bits[lo:hi], dim=-1, out=lane_mask[..., word])
+
+
+def _unfused_depth(
+ state: dict[str, torch.Tensor],
+ masks: list[torch.Tensor],
+ child_p: torch.Tensor,
+ child_tokens: torch.Tensor,
+ expanded: torch.Tensor,
+ child_hidden: torch.Tensor,
+ depth: int,
+ cumu_count: int,
+ verify_num: int,
+ num_slots: int,
+) -> None:
+ """The sequence the fused update replaces (the layer-gen and pool-update
+ kernels, the next depth's bool ancestor masks ``masks[depth + 1]`` and
+ their lane-mask words, the lane increments) on ``state``'s first rows."""
+ rows, width, k = child_p.shape
+ n = width * k
+ row = torch.arange(rows, device=_DEVICE)[:, None]
+ path = (child_p * state["scores"][:rows, :width, None]).reshape(rows, n)
+ tokens = child_tokens.reshape(rows, n)
+ layer, order = _bitonic_sort_64(path)
+ best = order[:, :k]
+ parent = best // k
+ state["frontier_index"][depth % 2][:rows] = cumu_count + best
+ state["scores"][:rows] = layer[:, :k]
+ state["tokens"][:rows] = tokens.gather(1, best)
+ state["hidden"][:rows] = child_hidden[row, parent]
+ # Device powf: CUDA pow with a tensor exponent.
+ decay = torch.pow(
+ torch.tensor(0.9999, device=_DEVICE), torch.tensor(depth + 1.0, device=_DEVICE)
+ )
+ new = slice(cumu_count, cumu_count + n)
+ child = torch.arange(n, device=_DEVICE)
+ state["pool_tokens"][:rows, new] = tokens
+ state["pool_scores"][:rows, new] = path * decay
+ state["pool_depths"][:rows, new] = depth + 1
+ state["pool_prev"][:rows, new] = expanded[:, :width].repeat_interleave(k, dim=1)
+ state["pool_next"][:rows, new] = -1
+ state["pool_side"][:rows, new] = torch.where(
+ child % k == k - 1, -1, cumu_count + child + 1
+ )
+ first_child = cumu_count + k * torch.arange(width, device=_DEVICE)
+ state["pool_next"][row, expanded[:, :width]] = first_child
+ # Work list, then the sort list's stable rank merge with the children.
+ head, kept = min(verify_num, cumu_count), min(verify_num, cumu_count + n)
+ merged = torch.cat([state["sort"][:rows, :head], layer], dim=1)
+ pos = torch.arange(merged.shape[1], device=_DEVICE)
+ above = (merged[:, None, :] > merged[:, :, None]) | (
+ (merged[:, None, :] == merged[:, :, None]) & (pos[None, :] < pos[:, None])
+ )
+ rank = above.sum(-1)
+ state["work"][:rows, :head] = state["sort"][:rows, :head]
+ state["work"][:rows, head : head + k] = layer[:, :k]
+ keep = rank < kept
+ state["sort"][row.expand_as(rank)[keep], rank[keep]] = merged[keep]
+ # The next depth's ancestors: the parents' rows, then each lane's own slot.
+ if (depth + 1) * k <= num_slots:
+ window = depth * k
+ masks[depth + 1][:rows, :, :window] = masks[depth][row, parent, :window]
+ _lane_mask_words(masks[depth + 1][:rows], state["lane_mask"][:rows])
+ state["positions"][:rows] += 1
+ state["slot_starts"][:rows] += k
+
+
+def _assert_bitwise_equal(actual: torch.Tensor, expected: torch.Tensor, name: str):
+ assert torch.equal(actual.view(torch.uint8), expected.view(torch.uint8)), name
+
+
+# K=2/4/8, including the sign bit of the 64-slot lane mask.
+ "rows,max_rows,k,steps",
+ [(3, 5, 2, 32), (3, 5, 4, 17), (3, 5, 8, 9), (32, 32, 8, 4)],
+)
+def test_draft_depth_update_matches_the_unfused_sequence(
+ rows: int, max_rows: int, k: int, steps: int, disabled: bool = False
+) -> None:
+ """A round of depths at random widths: from the same forward outputs the
+ fused update leaves every buffer bit-identical to the unfused sequence,
+ ties included (few distinct probabilities and path scores); rows past
+ ``rows`` (graph padding of the buffers) stay untouched."""
+ gen = torch.Generator(device=_DEVICE).manual_seed(1000 * rows + 10 * k + steps)
+ hidden_size = 1032 # 129 16-byte vectors per row
+ nodes, verify = max(1024, k * k * steps), max(64, k * (steps + 1) + 1)
+ num_slots = (steps - 1) * k
+ words = (num_slots + 63) // 64
+
+ def ints(shape, high=1000):
+ return torch.randint(-1, high, shape, generator=gen, device=_DEVICE)
+
+ def ties(shape):
+ return torch.randint(1, 5, shape, generator=gen, device=_DEVICE) / 4
+
+ state = {
+ "pool_tokens": ints((max_rows, nodes)),
+ "pool_scores": torch.rand((max_rows, nodes), generator=gen, device=_DEVICE),
+ "pool_depths": ints((max_rows, nodes)),
+ "pool_prev": ints((max_rows, nodes)),
+ "pool_next": ints((max_rows, nodes)),
+ "pool_side": ints((max_rows, nodes)),
+ "work": torch.rand((max_rows, verify + k), generator=gen, device=_DEVICE),
+ "sort": ties((max_rows, verify)).sort(dim=-1, descending=True).values,
+ "tokens": ints((max_rows, k)),
+ "scores": ties((max_rows, k)),
+ "hidden": torch.randn(
+ (max_rows, k, hidden_size), generator=gen, device=_DEVICE
+ ).to(torch.bfloat16),
+ "frontier_index": ints((2, max_rows, k)),
+ "positions": ints((max_rows, k)),
+ "slot_starts": ints((max_rows,)),
+ "lane_mask": ints((max_rows, k, words), 1 << 62),
+ }
+ # Depth 1's lane masks: lane r sees its own slot.
+ state["lane_mask"][:rows] = 0
+ state["lane_mask"][:rows, :, :1] = (1 << torch.arange(k, device=_DEVICE))[:, None]
+ fused = {name: t.clone() for name, t in state.items()}
+ # The unfused sequence's bool masks per depth: stale ancestors, own slots.
+ masks = [torch.empty(0)]
+ for s in range(1, steps):
+ mask = torch.rand((max_rows, k, s * k), generator=gen, device=_DEVICE) < 0.5
+ mask[:, :, (s - 1) * k :] = torch.eye(k, dtype=torch.bool, device=_DEVICE)
+ masks.append(mask)
+ root_children = torch.arange(1, k + 1, device=_DEVICE).repeat(rows, 1)
+
+ def fused_update(
+ child_p, child_tokens, expanded, child_hidden, width, depth, cumu_count
+ ):
+ eagle_harness_draft_depth_update(
+ child_p, child_tokens, expanded, child_hidden, fused["tokens"][:rows],
+ fused["scores"][:rows], fused["hidden"][:rows],
+ fused["frontier_index"][depth % 2][:rows], fused["pool_tokens"][:rows],
+ fused["pool_scores"][:rows], fused["pool_depths"][:rows],
+ fused["pool_prev"][:rows], fused["pool_next"][:rows], fused["pool_side"][:rows],
+ fused["work"][:rows], fused["sort"][:rows], fused["positions"][:rows],
+ fused["slot_starts"][:rows], fused["lane_mask"][:rows], _count(width),
+ depth, _count(cumu_count), _count(verify_num), num_slots,
+ ) # fmt: skip
+
+ cumu_count = 1 + k
+ verify_num = int(torch.randint(1, 65, (1,), generator=gen, device=_DEVICE))
+ for depth in range(1, steps):
+ width = int(torch.randint(1, k + 1, (1,), generator=gen, device=_DEVICE))
+ # The lane forward's outputs: K children per lane, the first width expanded.
+ child_p = ties((rows * k, k)).view(rows, k, k)
+ child_tokens = ints((rows * k, k)).view(rows, k, k)
+ child_hidden = torch.randn(
+ (rows * k, hidden_size), generator=gen, device=_DEVICE
+ ).to(torch.bfloat16)
+ expanded = [
+ root_children if depth == 1 else s["frontier_index"][(depth + 1) % 2][:rows]
+ for s in (state, fused)
+ ]
+ if disabled:
+ fused_update(
+ child_p,
+ child_tokens,
+ expanded[1],
+ child_hidden.view(rows, k, -1),
+ 0,
+ depth,
+ 0,
+ )
+ torch.cuda.synchronize()
+ for name, expected in state.items():
+ _assert_bitwise_equal(fused[name], expected, name)
+ return
+ _unfused_depth(
+ state, masks, child_p[:, :width], child_tokens[:, :width], expanded[0],
+ child_hidden.view(rows, k, -1), depth, cumu_count, verify_num, num_slots,
+ ) # fmt: skip
+ fused_update(
+ child_p, child_tokens, expanded[1], child_hidden.view(rows, k, -1), width,
+ depth, cumu_count,
+ ) # fmt: skip
+ cumu_count += width * k
+ for name, expected in state.items():
+ _assert_bitwise_equal(fused[name], expected, f"{name} at depth {depth}")
+
+
+def test_disabled_chain_depth_preserves_pool_and_frontier():
+ test_draft_depth_update_matches_the_unfused_sequence(3, 5, 1, 7, disabled=True)
+
+
[email protected]("verify_num", [1, 16])
+def test_write_verify_tree(verify_num: int) -> None:
+ """Ranked nodes' tokens and parent slots, the rest the root with parent -1,
+ in each request's row of the next round's maps."""
+ bs, nodes, slots = 3, 64, 16
+ generator = torch.Generator().manual_seed(verify_num)
+ prev = torch.full((bs, nodes), -1, dtype=torch.int64)
+ for node in range(1, nodes):
+ prev[:, node] = torch.randint(0, node, (bs,), generator=generator)
+ tokens = torch.randint(0, 1000, (bs, nodes), generator=generator)
+ # An ancestor-first ranking: each node's parent is ranked before it.
+ # A padded row past the live ones is never written.
+ ranked = torch.zeros((bs + 1, 16), dtype=torch.int64)
+ for b in range(bs):
+ chosen = [0]
+ while len(chosen) < 16:
+ node = int(torch.randint(1, nodes, (1,), generator=generator))
+ if node not in chosen and int(prev[b, node]) in chosen:
+ chosen.append(node)
+ ranked[b] = torch.tensor(chosen)
+ root = torch.tensor([7, 8, 9, 6], dtype=torch.int32)
+ rows = torch.tensor([5, 2, 9, 11], dtype=torch.int64)
+ prev, tokens = (torch.cat([t, t[:1]]) for t in (prev, tokens))
+ input_map = torch.zeros((12, slots), dtype=torch.int32, device=_DEVICE)
+ parent_map = torch.zeros((12, slots), dtype=torch.int32, device=_DEVICE)
+ eagle_harness_write_verify_tree(
+ ranked.to(_DEVICE), tokens.to(_DEVICE), prev.to(_DEVICE), root.to(_DEVICE),
+ rows.to(_DEVICE), input_map, parent_map, _count(bs), _count(verify_num),
+ ) # fmt: skip
+ assert (input_map[11] == 0).all() and (parent_map[11] == 0).all()
+
+ for b in range(bs):
+ want_tokens = [int(root[b])] * slots
+ want_parents = [-1] * slots
+ for i in range(verify_num):
+ node = int(ranked[b, i])
+ want_tokens[i] = int(tokens[b, node])
+ parent = int(prev[b, node])
+ want_parents[i] = ranked[b, :i].tolist().index(parent) if i else -1
+ assert input_map[rows[b]].tolist() == want_tokens
+ assert parent_map[rows[b]].tolist() == want_parents
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, *sys.argv[1:]]))
diff --git a/tests/tokenspeed_round/test_tree_rejection_gpu.py b/tests/tokenspeed_round/test_tree_rejection_gpu.py
new file mode 100644
index 0000000..97fbc0c
--- /dev/null
+++ b/tests/tokenspeed_round/test_tree_rejection_gpu.py
@@ -0,0 +1,189 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""Draft-tree verify on the flashinfer backend (``TreeRejectionSampler``):
+greedy and uncut rows skip their probability work without changing a
+decision, for chosen children and for children drawn from the draft q
+(``DraftTreeQ``, read at each request's pool slot)."""
+
+import pytest
+import torch
+
+pytest.importorskip("tokenspeed")
+from tokenspeed_kernel.ops.sampling.cuda import fused_topk_topp_renorm
+from tokenspeed_kernel.ops.sampling.flashinfer import softmax
+from eagle_harness.tokenspeed.tree_round.ops.rejection import (
+ residual_sample,
+ tree_reject_sample,
+)
+
+from tokenspeed.runtime.layers.logits_processor import LogitsProcessorOutput
+from tokenspeed.runtime.sampling.backends.base import SamplingBackendConfig
+from tokenspeed.runtime.sampling.backends.flashinfer import FlashInferSamplingBackend
+from tokenspeed.runtime.sampling.sampling_batch_info import SamplingBatchInfo
+from tokenspeed.runtime.sampling.sampling_params import SamplingParams
+from tokenspeed.runtime.sampling.tree_verify import DraftTreeQ, TreeVerifyBatch
+
+from eagle_harness.tokenspeed.tree_rejection import TreeRejectionSampler
+
+pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA")
+
+
+def _backend(bs: int, n: int, vocab: int) -> FlashInferSamplingBackend:
+ backend = FlashInferSamplingBackend(
+ SamplingBackendConfig(
+ synthetic_acceptance_length=None,
+ max_bs=bs,
+ max_draft_tokens_per_req=n,
+ max_req_pool_size=bs + 1,
+ vocab_size=vocab,
+ device="cuda",
+ enable_speculative_sampling=False,
+ sampling_stream="batch",
+ logprob_order="torch",
+ )
+ )
+
+ backend.bind_tree_sampler(TreeRejectionSampler)
+ return backend
+
+
+# Greedy (temperature 0 and top-k 1), uncut, top-k + top-p, top-p only and top-k only.
+SKIP_PARAMS = [
+ dict(temperature=0.0, top_k=-1, top_p=1.0),
+ dict(temperature=1.0, top_k=-1, top_p=1.0),
+ dict(temperature=0.8, top_k=20, top_p=0.95),
+ dict(temperature=0.7, top_k=1, top_p=1.0),
+ dict(temperature=0.7, top_k=-1, top_p=0.9),
+ dict(temperature=1.2, top_k=5, top_p=1.0),
+]
+SKIP_BS, SKIP_N, SKIP_NC = 8, 16, 32
+
+
+def _skip_problem(vocab: int, sampled_tree: bool, seed: int):
+ """Random logits and random trees whose tokens often hit their parent
+ row's argmax; a sampled tree draws each sampled request's children from a
+ q slot per parent (greedy requests stay deterministic, as the drafter
+ leaves them)."""
+ dev = "cuda"
+ gen = torch.Generator().manual_seed(seed)
+ bs, n, nc = SKIP_BS, SKIP_N, SKIP_NC
+ params = [SKIP_PARAMS[i % len(SKIP_PARAMS)] for i in range(bs)]
+ greedy = [p["temperature"] == 0.0 or p["top_k"] == 1 for p in params]
+ logits = torch.randn((bs * n, vocab), generator=gen) * 3
+ best = logits.argmax(-1).view(bs, n)
+ parents = torch.full((bs, n), -1, dtype=torch.int32)
+ tokens = torch.randint(0, vocab, (bs, n), generator=gen, dtype=torch.int32)
+ rows = bs + 1
+ q = torch.softmax(torch.randn((rows, n, nc), generator=gen) * 2, -1)
+ q_ids = torch.randint(0, vocab, (rows, n, nc), generator=gen, dtype=torch.int32)
+ slot = torch.full((rows, n), -1, dtype=torch.int32)
+ pos = torch.zeros((rows, n), dtype=torch.int32)
+ for b in range(bs):
+ used = int(torch.randint(n // 2, n + 1, (1,), generator=gen))
+ free = [torch.randperm(nc, generator=gen).tolist() for _ in range(n)]
+ for i in range(1, used):
+ parent = int(torch.randint(0, i, (1,), generator=gen))
+ parents[b, i] = parent
+ if float(torch.rand((1,), generator=gen)) < 0.6:
+ tokens[b, i] = best[b, parent]
+ if sampled_tree and not greedy[b]:
+ slot[b + 1, i] = parent
+ pos[b + 1, i] = free[parent].pop()
+ q_ids[b + 1, parent, pos[b + 1, i]] = tokens[b, i]
+ tokens[b, used:] = tokens[b, 0]
+ draft_q = DraftTreeQ(q=q.to(dev), q_ids=q_ids.to(dev), slot=slot.to(dev), pos=pos.to(dev)) if sampled_tree else None
+ return params, logits.to(dev), tokens.to(dev), parents.to(dev), draft_q
+
+
+def _full_probability_verify(backend, logits, tokens, parents, draft_q, req):
+ """The verify with every row's probabilities computed: the softmax cut
+ and renormalized out of place (uncut rows keep the softmax values),
+ torch.argmax of those rows, and the rejection kernels on every row."""
+ bs, n = tokens.shape
+ pools = backend.speculative_sampling_pools()
+ temperatures = pools.temperature[req].repeat_interleave(n)
+ top_ks = pools.top_k[req].repeat_interleave(n)
+ top_ps = pools.top_p[req].repeat_interleave(n)
+ probs = softmax(logits, temperature=temperatures)
+ cut = fused_topk_topp_renorm(probs, top_ks, top_ps, in_place_skip=False)
+ uncut = (top_ks >= logits.shape[1]) & (top_ps >= 1.0)
+ target = torch.where(uncut[:, None], probs, cut)
+ argmax = target.argmax(dim=-1)
+ never_greedy = torch.zeros_like(top_ks)
+ q = draft_q if draft_q is not None else backend._tree_sampler.no_draft_q
+ path = torch.empty((bs, n), dtype=torch.int32, device="cuda")
+ predict = torch.full((bs * n,), -1, dtype=torch.int32, device="cuda")
+ accept_length = torch.empty(bs, dtype=torch.int32, device="cuda")
+ last_row = torch.empty(bs, dtype=torch.int64, device="cuda")
+ tree_reject_sample(
+ target, tokens, parents, req if draft_q is not None else None, q.slot,
+ q.pos, q.q, q.q_ids, backend._coins_buf[:bs, :n], never_greedy, argmax,
+ path, predict, accept_length, last_row,
+ ) # fmt: skip
+ residual_sample(
+ target, last_row, backend._final_coins_buf[:bs], never_greedy, argmax,
+ accept_length, predict, n,
+ ) # fmt: skip
+ return path, predict, accept_length, last_row
+
+
[email protected]("sampled_tree", [False, True])
+def test_verify_tree_skips_greedy_and_uncut_rows_without_changing_decisions(
+ sampled_tree: bool,
+) -> None:
+ """Greedy rows (no probabilities, the logits' argmax) and uncut rows
+ (no renorm) decide every child, path and bonus exactly as the full
+ probability path does, across mixed batches and random trees."""
+ bs, n, vocab = SKIP_BS, SKIP_N, 32768
+ backend = _backend(bs, n, vocab)
+ pool = list(range(1, bs + 1))
+ req = torch.tensor(pool, dtype=torch.int64, device="cuda")
+ accepted = {True: 0, False: 0}
+ for seed in range(3):
+ params, logits, tokens, parents, draft_q = _skip_problem(vocab, sampled_tree, seed)
+ sampling_params = []
+ for i, kwargs in enumerate(params):
+ sp = SamplingParams(**kwargs)
+ sp.resolve_seed(f"skip_{seed}_{i}")
+ sp.normalize(None)
+ sampling_params.append(sp)
+ backend.prepare_step(
+ request_ids=[f"skip_{seed}_{i}" for i in range(bs)],
+ request_pool_indices=pool,
+ sampling_params_list=sampling_params,
+ num_tokens_per_req=n,
+ )
+ expected = _full_probability_verify(backend, logits, tokens, parents, draft_q, req)
+ tree = TreeVerifyBatch(
+ parents=parents,
+ depths=torch.zeros_like(parents),
+ draft_q=draft_q,
+ )
+ info = SamplingBatchInfo(
+ req_pool_indices=req,
+ valid_cache_lengths=torch.zeros(bs + 1, dtype=torch.int32, device="cuda"),
+ vocab_size=vocab,
+ device="cuda",
+ )
+ predict, accept_length = backend.verify(
+ LogitsProcessorOutput(next_token_logits=logits.clone()),
+ info,
+ tokens,
+ tree=tree,
+ )
+ path = backend.accepted_path(bs, n)
+ want_path, want_predict, want_length, want_last = expected
+ assert torch.equal(accept_length, want_length)
+ assert torch.equal(path, want_path)
+ assert torch.equal(backend._tree_sampler.last_row[:bs], want_last)
+ for b in range(bs):
+ length = int(want_length[b])
+ assert torch.equal(predict[b * n : b * n + length], want_predict[b * n : b * n + length])
+ accepted[params[b]["temperature"] == 0.0 or params[b]["top_k"] == 1] += length - 1
+ # Both kinds of rows accept children, so the comparison covers acceptance.
+ assert accepted[True] > 0 and accepted[False] > 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tools/engine_release.py b/tools/engine_release.py
index 1664dca..3fcc87f 100644
--- a/tools/engine_release.py
+++ b/tools/engine_release.py
@@ -32,7 +32,7 @@ UPLOAD_CHANNELS = (*CHANNELS, "harness", "rocm-runtime")
ROCM_LOCK = Path(__file__).resolve().parents[1] / "docker/rocm/requirements.lock"
REQUIRED = {
"harness": {"eagle-harness"},
- "cu130": {"sglang", "vllm", "tokenspeed", "tokenspeed-kernel", "tokenspeed-scheduler"},
+ "cu130": {"sglang", "vllm", "tokenspeed", "tokenspeed-kernel", "tokenspeed-scheduler", "tokenspeed-engine"},
"rocm": {"sglang"},
}
WHEEL_NAME = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.+\-]*\.whl")
diff --git a/tools/third_party_headers.json b/tools/third_party_headers.json
index d70ecac..f14f20f 100644
--- a/tools/third_party_headers.json
+++ b/tools/third_party_headers.json
@@ -1,5 +1,11 @@
{
"files": [
+ {
+ "path": "eagle_harness/tokenspeed/tree_round/ops/csrc/tvm_ffi_utils.h",
+ "notice": "/*\n * Copyright (c) 2023 by FlashInfer team.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n",
+ "modified": true,
+ "absent_in_baseline": true
+ },
{
"path": "eagle_harness/kernels/gdn_tree_chunk_flydsl.py",
"notice": "# Copyright (c) 2026 Advanced Micro Devices, Inc.\n# SPDX-License-Identifier: Apache-2.0\n",