## Summary
Forward the effective `--trust-remote-code` setting from `ts serve` to
SMG so the gateway can render text chat with a checkpoint's custom
Python tokenizer. The engine receives the supplied trust flags in order.
When both forms are present, the last form determines whether the
gateway receives the opt-in.
## Dependency
This change depends on the SMG Python renderer and its startup opt-in.
[smg-project/smg#9376](https://github.com/smg-project/smg/pull/9376)
The `tokenspeed-smg` dependency is updated to `1.16.0.post20261203`.
## Test Plan
- `pre-commit run --all-files` passed.
- `python -m pytest -q test/cli/test_argsplit.py` passed 47 tests,
including defaults, both flag forms, and repeated settings.
- Exercised `ts serve` offline with a locally built SMG wheel, a local
checkpoint, and a CPU fake backend. The enabled case matched the
reference Python prompt token IDs. The disabled case returned the opt-in
error.
---------
Signed-off-by: tuanzhangCS <26617745+tuanzhangCS@users.noreply.github.com>
Signed-off-by: tuanzhangCS <tuan@lightseek.org>
Co-authored-by: tuanzhangCS <26617745+tuanzhangCS@users.noreply.github.com>
Co-authored-by: minedec <37043133+minedec@users.noreply.github.com>
## Summary
Follow up on #3667 by requiring [torch-npu-memory-saver
0.1.7](https://pypi.org/project/torch-npu-memory-saver/0.1.7/) in both
the NPU kernel backend and the Ascend extra. Update the installation
hint, serving guide, and exact-version packaging test. The allocator
continues to use ABI 5.
## Why TokenSpeed NPU workers need 0.1.7
- **Prefill fragmentation.** Version 0.1.6 required
`expandable_segments:False` for the entire worker. Ordinary prefill
activations with varying shapes could therefore accumulate unusable
gaps, and enabling expandable segments caused Saver initialization to
fail. With 0.1.7 operators can start the worker with
`PYTORCH_NPU_ALLOC_CONF=expandable_segments:True`. Expansion is disabled
only around Saver-managed allocations and ACL graph capture, then
restored for ordinary allocations. The default in the launch example
stays unchanged.
- **Concurrent suspend and pinned host memory.** A Prefill/Decode pair
backing up weights or other managed bytes at the same time can exhaust
pinned host memory. Previously `aclrtMallocHost` error `207001` aborted
suspend. The new allocator logs a warning, falls back to pageable host
memory for that allocation, and completes the synchronous copy before
unmapping the device pages. Other ACL errors still propagate.
- **Failed allocator restore with waiting callers.** If PTA fails to
restore the expandable-segment setting, a thread that already passed the
initial health check may be waiting on the pool lock. Version 0.1.7
checks again after acquiring that lock. Queued `assert_active`, `pause`,
and `resume` raise a worker-restart error before changing pool state.
The implementation and platform wheel are in the [standalone library
release](https://github.com/yanlonghu/torch_npu_memory_saver/releases/tag/v0.1.7).
This TokenSpeed PR selects that release on Ascend.
## Validation
- Installed 0.1.7 by name from PyPI on A2. Independently installed the
published CPython 3.12/Linux AArch64/CANN 9.0.0 wheel after downloading
it from the GitHub release and checking its SHA-256.
- Ran the current TokenSpeed NPU adapter's four real-device cases with
expandable segments enabled and disabled (8 passes). The three
standalone NPU device cases and all three queued-failure cases passed on
the installed wheel.
- Ran Qwen3 TP2 with the release wheel in the established protocol-3
integration fixture. CPU-backed partial update and full discard/refill
passed. The refilled instance and cold start with the new checkpoint
matched at all 24 output token positions (maximum absolute logprob
difference 0).
- All 31 kernel setup tests passed in isolation, covering
backend-specific package metadata. CUDA/ROCm execution was not tested on
hardware.
- On A3 (CANN 8.5 / CPython 3.11), built and installed a separate
platform wheel from the checksum-verified PyPI sdist. The three
queue-failure cases and three device tests passed.
- LongCat Lite P8+D8 on A3, using the CANN 8.5 wheel built from the
published 0.1.7 sdist: all 16 ranks loaded the matched wheel and native
library. Prefill and Decode suspended and resumed concurrently. All
seven ordinary prefill activation samples (four before suspend and three
after resume) belonged to expandable segments in the default pool. Five
prompts matched across suspend/resume at all 40 output token positions,
with zero absolute logprob difference.
Signed-off-by: yanlonghu <19688573+yanlonghu@users.noreply.github.com>
Co-authored-by: yanlonghu <19688573+yanlonghu@users.noreply.github.com>
Retire the opt-in InstantTensor backend to reduce weight-loader
maintenance. Existing `--load-format instanttensor` invocations must
select a supported format such as `auto` or `safetensors`.
Validation: existing loader regression tests and repository pre-commit
checks passed.
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
## Summary
Adds `--load-format runai_streamer` and `--model-loader-extra-config` to
stream `*.safetensors` checkpoints directly from local directories or
cloud object-store URIs (`gs://`, `s3://`) via [Run:ai Model
Streamer](https://github.com/run-ai/runai-model-streamer).
### Key Changes
- **Loader & CLI wiring**: Added `LoadFormat.RUNAI_STREAMER`,
`RunaiModelStreamerLoader`, and `runai_streamer_weights_iterator`
supporting `concurrency`, `memory_limit`, and `distributed` options
passed via `--model-loader-extra-config` (parsed and validated once in
`ServerArgs` and `LoadConfig`). `distributed=true` with a
rank-restricted `checkpoint_load_group` raises explicitly rather than
silently downgrading.
- **L3 checkpoint identity**: Normalized `runai_streamer` to
`safetensors` and stripped I/O-only tuning knobs (`concurrency`,
`memory_limit`, `distributed`) in `l3_checkpoint_id` so replicas with
different loader tuning share the same L3 KV namespace.
- **Object-store metadata sync & byte-range reads (`object_store.py`)**:
- Syncs only non-weight metadata files (`config.json`, tokenizer assets,
`model.safetensors.index.json`, custom `*.py`, `encoding/*`) into a
user-owned (`0o700`) cache under `--download-dir`, `$HF_HOME`,
`$XDG_CACHE_HOME`, or `~/.cache/tokenspeed/object-store-meta` using one
resolved path across config, tokenizer, and loader calls.
- Verifies cache directory/file ownership and rejects symlinks and
path-traversal object keys; tracks GCS `generation` / S3 `ETag` in a
versioned manifest so updated remote metadata refreshes automatically.
- Adds `RemoteSafetensorsFile`, `RemoteSafetensorsSlice` (with a shared
reusable `ThreadPoolExecutor` for sequential row prefetching and
`float8_e8m0fnu` / `float4_e2m1fn_x2` dtype parity), and
`open_safetensors_slice` so filtered mixed shards and sharded host
embedding tables (e.g. DeepSeek V4.1) read only the needed byte ranges
without streaming rejected tables.
- **Docs & tests**: Documented the new flags in
`docs/configuration/server.md` and added unit tests in
`test/runtime/test_runai_streamer_loader.py`.
## Verification
- `pre-commit run --all-files`: passed.
- `pytest test/runtime/test_runai_streamer_loader.py`: 22 passed, 1
skipped (optional `runai_model_streamer` local parity test skipped in
CPU-only environment).
## Checklist Before Undrafting
- [ ] Run GPU memory release/resume regression verification with
`--load-format runai_streamer` (`distributed: true`) confirming 0 bytes
remain in ordinary Torch CUDA allocator segments (`segment_pool_id=(0,
0)`) after release and resumed execution remains correct.
- [ ] Run multi-rank GPU integration test with `runai-model-streamer`
installed (`distributed: true` and local parity test unskipped).
---------
Signed-off-by: Fan Yang <250624800+fanyang-real@users.noreply.github.com>
## Purpose
Allow Ascend workers to suspend selected weights, KV and ACL graph
storage between rollout windows and resume at the original virtual
addresses. The original graph executable and HCCL communicator stay
resident. This is the standalone-allocator alternative to #3530.
## Design and use
TokenSpeed controls tensor ownership, transfer ordering, weight-update
commits and replica agreement. Protocol 3 extends protocol 2's
weight-update agreement to release/resume preflight and per-rank
completion. The [standalone
allocator](https://github.com/yanlonghu/torch_npu_memory_saver/commit/7d1a06db2a36b725ef270c6a62e5f78f0eeeae60)
owns the PTA pools, remapping, backup and the final allocator cache
trim.
Use `--device npu --enable-memory-saver` with `--weight-memory-policy
cpu_backup` or `discard`.
| Target state | KV and prefix behavior |
| --- | --- |
| Fully CPU-backed, weights unchanged | Resume restores the KV payload
and keeps valid prefix hits. |
| Weight update, including a same-version partial update | Flush old
prefixes before writing weights. Clear a stale sleeping KV image before
registering it for transfer. |
| Discard target | Drop old KV. After a weight release, restore
mappings, reload the complete target and commit before waking KV. |
The immutable KV layout uses the existing runtime allocator.
Page-transfer staging wakes with KV, so cache-only work can proceed
while the graph remains asleep. Model and idle forwards still require
their pools to be active. CUDA/ROCm retain their current adapter,
allocation lifetime and cache policy.
## Installation
With matching CANN, PyTorch and PTA installed, run:
```bash
TOKENSPEED_KERNEL_BACKEND=npu python -m pip install -e ./tokenspeed-kernel/python ./tokenspeed-engine -e ./python
```
The NPU backend resolves [torch-npu-memory-saver 0.1.6 on
PyPI](https://pypi.org/project/torch-npu-memory-saver/0.1.6/) (native
ABI 5). The source distribution builds against the active toolkit. A
[prebuilt CPython 3.12 / Linux AArch64
wheel](https://github.com/yanlonghu/torch_npu_memory_saver/releases/tag/v0.1.6)
is available for the tested A2 CANN 9.0.0 stack. The [serving
guide](https://github.com/yanlonghu/tokenspeed/blob/a03a9a083bbe78670518551111d7a13f2fa86518/docs/serving/ascend-memory-saver.md)
lists the six PTA 2.9.0-730 backports and install constraints.
## Validation
Latest KV changes:
[a03a9a08](https://github.com/yanlonghu/tokenspeed/commit/a03a9a083bbe78670518551111d7a13f2fa86518).
| Coverage | Observed result |
| --- | --- |
| A2 / 910B3, CANN 9.0.0, patched PTA 2.9, Qwen3-0.6B TP2 | An unchanged
CPU-backed target kept all 256 cached prefix tokens. Same-version
partial updates, full updates and discard refills each went from 256
hits to zero on the first request and back to 256 on the second. Eight
generated tokens per update path matched an independent launch in the
corresponding cold or warm state. |
| A3 / 910C, CANN 8.5.0, PTA 2.9, two-layer Qwen3 | The same cache-hit
transitions passed. Updating only the first value projection changed all
267 shared-prefix V rows. All eight resulting tokens and their
selected-token log probabilities matched a separate cold launch of the
modified checkpoint. Separate TP2 AIV graph coverage also passed. |
| Independent KV wake on both boards | With the graph pool still
unmapped, the device copied and zeroed KV pages. The original graph
subsequently replayed after its own wake. |
| Platform isolation | CUDA/HIP CPU adapter fixtures, cache arena
coverage and package dependency tests passed. Physical GPU regression
was unavailable. |
The CPU backup covers the allocated KV arena. If weights change while a
snapshot is asleep, the current allocator copies it back before
TokenSpeed clears it. That transfer is redundant; its latency and peak
host memory were not benchmarked in this round.
<details>
<summary>Earlier integration and operator qualification (prior allocator
versions)</summary>
The host and runtime use the same bootstrap API. Ascend ranks agree on
the memory protocol before saver-specific HCCL initialization. Release
and resume carry an optional transition ID separate from the request ID.
The feature uses upstream MHA dispatch. General multi-query
FIA/Triton/RoPE changes have been split out. Historical multi-query
results below used that additional operator support.
- **A2 / CANN 9.0.0 / patched PTA 2.9.** Reproduced the KV and MoE
failures on the old head. The frozen build passed all 9 targeted device
tests and 23 selected startup tests. After discarding Qwen3-0.6B TP2
weights and reloading all 313 checkpoint entries, both prompts matched
checkpoint B's cold launch across 24 generated positions with zero
selected-token log-probability difference.
- **A3 / CANN 8.5.0 / PTA 2.9.** All 10 device/startup tests and 17
native lifecycle tests passed. Both HCCL AIV TP2 ranks rejected mixed
protocol versions. For three suspend/resume cycles the managed graph
pool reached zero mapped bytes and the original graph reproduced all
4,096 AllGather values per rank at the same output address.
- **Isolation.** The MoE test exercises real NPU workspace allocation
with a small test kernel plan. The CUDA/HIP communication and allocation
fixtures passed on CPU. No physical GPU run was available in this round.
Packaging commit
[`6b24fbad`](https://github.com/yanlonghu/tokenspeed/commit/6b24fbad4feb3a93ef0188bcabd6d8427fe0fe49)
was checked separately. Pip downloaded the public source archive and
release wheel, and both SHA256 digests matched. Only the NPU kernel
metadata requires the saver. The 29 packaging tests passed. On A2/CANN
9.0.0 with patched PTA 2.9, the wheel loaded its own ABI 4 library. The
standalone replay test and both TokenSpeed graph policies (`discard`,
`cpu_backup`) passed with three suspend/resume cycles each and exact
output checks.
Serving integration
[`fb681265`](https://github.com/yanlonghu/tokenspeed/commit/fb68126554bc57d597149909eb2b1d1261764d88)
includes upstream main `67573412`. The Ascend saver device forwards the
host's recurrent-state retirement slots and fence after checking that
managed pools are active. Full Qwen3 disk recovery accepts known rotary
metadata and an output head owned by another pipeline stage. Required
local checkpoint entries remain mandatory and duplicates still fail. If
a Mooncake update and cleanup both fail, the NPU saver returns the first
update error.
- A2 / CANN 9.0.0 / patched PTA 2.9, Qwen3-0.6B TP2 eager: two ranks
consumed 313 entries each. After discarding weights and KV, reloading
checkpoint B and then resuming KV, all 24 generated tokens matched a
separate cold launch of B. The maximum absolute difference in the
selected tokens' log probabilities was 0.0. The initial checkpoint A
produced a different first token.
- A2 native MHA, one input token, verification width four, captured
batch two: 12 active output tokens matched across the eager, ACL replay
and restored runs. The standalone and bundled implementations shared the
same eager reference. The installed A2 kernel registry lacks a
compatible GDN/Mamba2 multi-token verify backend, so this does not
qualify a hybrid model.
- The matching Linux ARM64 host, control and serving suites passed 48
tests. The A2-host Python regression passed 12
protocol/weight-error/device-guard tests. Native ABI 4 rejects stale ABI
3 library overrides before allocator use. An actual old native binary
and matching ABI 4 binary were tested through both Python loaders.
- The hardware runs used `0907c0a4`. Only a unit-test mock changed
between that revision and `fb681265`.
### November 24 validation
At
[`62e77514`](https://github.com/yanlonghu/tokenspeed/commit/62e775143770627aad22f01422adf0e1b5972c48),
install the pinned [standalone 0.1.4
source](https://github.com/yanlonghu/torch_npu_memory_saver/commit/866357c48048459d69522e311d56b8e1f6dfaed7).
The native library retains mapped storage when an HCCL registration
result leaves peer state uncertain. A cache-trim callback failure is
reported on the same pause call. TokenSpeed cancels an agreed protocol 3
release before a deferred L3 flush can yield to release processing.
- On A2/910B3, CANN 9.0.0 and patched PTA 2.9, the installed standalone
wheel supplied the native library loaded by both Qwen3-0.6B BF16 TP2
workers. All 32 generated token positions matched after release/resume,
and the launcher exited normally. Both single-device graph policy tests
passed. Both rank logs placed the first AIV-buffer release after
restored generation.
- In a separate two-rank AIV AllGather test, each rank captured once and
replayed its original graph through three suspend/resume cycles. The
graph output address and the 401 MiB HCCL arena per rank stayed stable.
Managed mapped and physical bytes reached zero on both ranks during
every pause.
- All 13 native fault and lifecycle tests passed, including errors
before and after state changes in each HCCL registration call. These
faults were injected into the native allocator test harness. The Rust
gate and its regression test are byte-identical to [the fix verified in
#3530](https://github.com/lightseekorg/tokenspeed/pull/3530/commits/bb684a4f2b7b69282bdba0f96902d0ec2d47cc85),
including one-sided cancellation while a two-rank L3 flush is pending.
Production A3 ACK failures were not injected.
- The supplemental mixed-platform Python run had 73 passes, two
CUDA-only skips and four failures during lazy FlashInfer import with the
inherited mock CUDA version `test`. With the actual Ascend cache
metadata imported before the fixture, all eight cache-table cases passed
on the same source.
### Earlier validation
For the 0.1.3 update, the source package and the installed A2 wheel were
checked separately. The wheel passed its A2 graph test and mapped its
bundled native library. Through the TokenSpeed adapter, both A2
single-device graph policies passed. Under TP2 AIV, each rank captured
once and replayed the same graph for three suspend/resume cycles,
verifying 524,288 bytes of AllGather output per rank per cycle. The A2
adapter skipped HCCL registration. A freshly built Qwen3-0.6B BF16 TP2
service also released and resumed weights, KV and graph memory. All 32
output tokens matched and the launcher exited with status zero. A3
full-model and segment-reuse runs remain pending access to the hardware.
Earlier results with 0.1.1:
- Atlas A2 / 910B3, CANN 9, patched PTA 2.9, Qwen3-0.6B TP2, protocol 3,
HCCL AIV. All three full suspend/resume cycles reproduced all 32 tokens
for each of four prompts. Both ranks loaded the native library installed
from the PyPI release.
- A two-tensor partial disk update under `cpu_backup` and a complete
311-tensor disk refill under `discard` matched a fresh launch of the
updated checkpoint. KV resume before the complete refill was rejected.
- The opt-in real-device integration test passed. Host/runtime
regressions without the optional package had 398 passes, three skips and
one failure: `test_the_guard_rejects_cuda_factories_before_they_run`
also fails on unmodified main with this CPU build of PyTorch. CUDA/ROCm
hardware was unavailable.
</details>
---------
Signed-off-by: yanlonghu <19688573+yanlonghu@users.noreply.github.com>
Co-authored-by: yanlonghu <19688573+yanlonghu@users.noreply.github.com>
Use `tokenspeed-xgrammar==0.2.9.post20261125` in place of upstream
XGrammar. The Python tokenizer serializer and the engine's embedded C++
compiler must use the same release; the new serialization format
requires regenerating the existing fixtures and rebuilding the engine.
Validation: 22 Python structural-tag tests and all 13 native grammar
tests passed.
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
Keep the gateway and its gRPC packages on the same published release so
their interfaces stay aligned.
Validation: `pre-commit run --all-files` (C++ formatting skipped; no C++
changes).
---------
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
## Summary
TokenSpeed still accepts Mooncake releases whose native C Store library
and Python Store binding abort on duplicate gflags registration when
loaded together. Require `tokenspeed-mooncake>=0.3.13.post20261119`,
which shares one Store core between the bindings, and update the cu129
install constraint to the same version.
Document the shared core required for native L3 clients and Python Store
clients to coexist. The release is available on
[PyPI](https://pypi.org/project/tokenspeed-mooncake/0.3.13.post20261119/)
and both [cu129](https://lightseek.org/whl/cu129/tokenspeed-mooncake/)
and [cu130](https://lightseek.org/whl/cu130/tokenspeed-mooncake/) wheel
indexes.
## Test Plan
- Downloaded the published cu129 and cu130 CPython 3.11 x86_64 wheels
and verified their SHA-256 hashes against the indexes.
- Installed each variant into a separate environment. Both C-first and
Python-first loading passed bidirectional TCP batch reads/writes and
three buffer registration/client teardown cycles; the surviving client
remained healthy after its peer closed.
- Dependency checks passed for both installed variants.
- `pre-commit run --all-files` passed.
Signed-off-by: FC-Li <robert_lexis@163.com>
Consume the latest published `tokenspeed-smg` gateway release
(`1.16.0.post20261118`).
The `python/pyproject.toml` pins move from the `20261117` snapshot to
the `20261118` snapshot:
- `tokenspeed-smg==1.16.0.post20261118`
- `tokenspeed-smg-grpc-proto==0.5.0.post20261118`
- `tokenspeed-smg-grpc-servicer==0.16.0.post20261118`
---------
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
Keep the gateway and gRPC packages on the same published snapshot to
avoid protocol drift. Keep Mooncake's runtime floor and CUDA 12.9
constraint aligned so both installation paths remain resolvable.
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
A `ut-runtime-1gpu-part-i (amd-mi355-1gpu)` install on a recent
unit-test run resolved `aiohttp` to 0.21.6: PyPI's CDN returned a bad
`Content-Type` for the multidict page on its simple index, pip skipped
the page, and with zero multidict candidates the resolver backtracked
the unpinned requirement through every release until one old enough not
to declare it. That release predates Python 3.12 (`ensure_future =
asyncio.async`), so `test/cli` collection died on a `SyntaxError` —
while pip still exited 0, leaving `pip_install_with_retry` (built for
this same CDN flake) nothing to retry.
Every `aiohttp >= 3.9` requires multidict, so flooring the requirement
turns this flake into a resolver failure the existing retry loop
handles; 3.9 is also the first line with cp312 wheels, so no admissible
release needs an sdist build on Python 3.12. Normal resolution is
unchanged (currently 3.14.5).
Requested in
https://github.com/lightseekorg/tokenspeed/pull/3526#issuecomment-6943004103
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
Match the kernel requirement's `.dev0` floor, so `0.1.1` pre-releases of
the engine, such as nightly `rc` builds, also satisfy
`tokenspeed-engine>=0.1.1`. A plain `>=0.1.1` excludes them, because
pre-releases sort before the final version.
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
Since #3511, TokenSpeed imports the scheduler from
`tokenspeed_engine.scheduler`, which `tokenspeed-engine` 0.1.0 does not
have. `tokenspeed-engine>=0.1.0` still allows those engines, so
upgrading TokenSpeed over an existing 0.1.0 install fails at import.
This bumps the engine base version to 0.1.1 and requires
`tokenspeed-engine>=0.1.1`. Nightlies already pin the exact engine they
build. A stable TokenSpeed release with this floor needs
`tokenspeed-engine` 0.1.1 published to PyPI first.
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
TokenSpeed currently installs two copies of the scheduler: the
standalone `tokenspeed-scheduler` wheel, and the build that
tokenspeed-engine links into `_host`. Each rank already serves the
runtime's `tokenspeed_scheduler` imports from the linked build. The
standalone wheel is only an extra dependency to build, pin and release
in step.
`tokenspeed_engine.scheduler` exposes the linked module with the same
names as `tokenspeed_scheduler`. The runtime and tests import it, and
`python/pyproject.toml` drops `tokenspeed-scheduler`. CI installs,
Docker images and the release image stop installing or pinning it. The
Mooncake L3 jobs now install the full engine, because their tests drive
the scheduler.
The standalone wheel is still published, and its release pipeline keeps
the version and publish stages. The stage that bumped TokenSpeed's
requirement and the scheduler check in the TokenSpeed preflight are
gone, since nothing downstream requires that wheel anymore.
Follow-up: stable TokenSpeed still requires `tokenspeed-engine>=0.1.0`.
That range includes engines without `tokenspeed_engine.scheduler`, so an
upgrade over an old engine needs an engine version bump to be enforced.
---------
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
Bump `tokenspeed-smg` 1.16.0.post20261113 → 1.16.0.post20261115 (smg
`a8898915`).
The new build adds `--grouped-dp-sticky {off,hash}` to `smg launch`
(smg-project/smg#6501). `ts serve` passes unknown flags through to `smg
launch`, which rejected this flag before, so grouped-DP sticky routing
could not be enabled from `ts serve`.
Test: installed the published x86_64 wheel; `python -m smg launch
--help` lists `--grouped-dp-sticky {off,hash}`. Proto and servicer pins
unchanged.
Signed-off-by: Fan Yang <250624800+fanyang-real@users.noreply.github.com>
## Summary
TokenSpeed's shared dependencies currently install the GPU-only
`torch_memory_saver` package on Ascend, including Linux ARM64. Move
`torch_memory_saver==0.0.9.post1` into the CUDA and ROCm
`tokenspeed-kernel` requirements, preserving its CUDA comment. CUDA 13,
CUDA 12.9, and ROCm retain the pin, and installations using the NPU
kernel path avoid that dependency. Ascend users still need the
documented NPU kernel installation path, since public PyPI can select a
CUDA kernel wheel.
Advance `tokenspeed-kernel` from `0.1.4` to `0.1.5` and raise
TokenSpeed's kernel minimum to `>=0.1.5.dev0`. This excludes older
kernel wheels that lack the saver dependency and accepts matching source
builds. The `.dev0` suffix follows the existing runtime dependency
convention.
## Release order
1. Publish the `tokenspeed-kernel` 0.1.5 CUDA 12.9, CUDA 13, and ROCm
wheels. Verify that each declares the saver pin and is available from
its intended package index.
2. Publish the TokenSpeed Runtime with the higher kernel minimum after
those compatible wheels are available.
The Biweekly release planner increments the greater of the source and
published kernel versions. With the source base at `0.1.5` and the
published version at `0.1.4`, it selects `0.1.6`. Releasing exactly
`0.1.5` requires the kernel release workflows from a `release/*` branch,
followed by Runtime publication. Before stable publication, use Runtime
and kernel packages built from the same checkout, or matching CUDA
13/ROCm nightly pairs that both include this change.
## Test Plan
- `pre-commit run --all-files` and `git diff --check` passed.
- Generated and compared setuptools `Requires-Dist` metadata for
TokenSpeed, CUDA 13, CUDA 12.9, ROCm, and NPU with Python 3.12.13 and
setuptools 83.0.0. The saver move and runtime kernel minimum were the
only dependency changes. NPU dependencies were identical.
- Verified that the minimum rejects `0.1.4` and accepts the generated
`0.1.5` release, source, and nightly versions.
- No accelerator hardware regression tests were run.
Signed-off-by: yanlonghu <19688573+yanlonghu@users.noreply.github.com>
Co-authored-by: yanlonghu <19688573+yanlonghu@users.noreply.github.com>
Keep the gateway, protocol bindings and servicer on their latest
published releases so runtime installations use the updated SMG packages
together.
Validation: pre-commit (all non-C++ hooks), `pip check`, and the
existing SMG parser availability test passed.
---------
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
<!-- Headings and layout are optional. Include change context and
validation
(checks performed or planned, or why testing was not run or is not
applicable)
anywhere in the description. -->
## Summary
<!-- What changed and why? -->
## Test Plan
<!-- How was this validated? -->
## Summary
Earlier removals left some runtime code with no callers. This PR deletes
it. Nothing that runs changes.
- **Six modules nothing imports:**
- `python/tokenspeed/runtime/utils/dispatch.py` lost its last user in
#2603.
- `python/tokenspeed/runtime/utils/text.py` and
`python/tokenspeed/runtime/utils/exceptions.py` lost theirs in #2718.
- `python/tokenspeed/runtime/utils/custom_ops.py` lost its last user in
#2310.
- `python/tokenspeed/runtime/metrics/utils.py` lost its last user in
#2618.
- `python/tokenspeed/runtime/distributed/device_communicators/utils.py`
lost its last user in #991.
- **`python/tokenspeed/runtime/utils/common.py`:**
- `broadcast_pyobj`, `get_zmq_socket`, `MultiprocessingSerializer` and
the `step_counter` global, along with the imports only they used. The
Python engine that #2718 removed was their last user.
- `log_info_on_rank0` now uses the module's `dist` import instead of
importing it again.
- **No callers:** `gptq_marlin_moe_repack`, `marlin_moe_permute_scales`,
`FusedMoeWeightScaleSupported` and the `decrypt` stub.
- **`pybase64`:** only `python/tokenspeed/runtime/utils/common.py`
imported it. It is dropped from the dependencies, the environment report
and the kernel ARM unit-test install.
`python/tokenspeed/runtime/metrics/collector.py` stays, even though only
tests import it. The `ts-metrics` fixtures are generated from it.
## Testing
- `ruff check --select F` is clean on the touched files. A scan of
`python/tokenspeed` finds no remaining references to any removed name.
- Every touched module imports.
- `pre-commit run --all-files` passes.
- The 16 test files that import a touched module give the same results
on this branch and on its base: 517 passed, 41 skipped and 1 failed.
- The failure,
`test_modelopt_mixed_config.py::test_attention_dp_lm_head_uses_mixed_quantization`,
also fails on main.
Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
## Summary
SMG's gateway now reaches TokenSpeed engines over the msgpack wire
directly
(its direct lane), for every role, so the in-process Python frontend
(`AsyncLLM`) and the gRPC servicer path have no serving caller left.
This PR
implements the wire revision the lane speaks in the engine host, moves
`ts
serve` onto the lane, and removes `AsyncLLM` with the code only it used.
Commits:
1. **feat(engine): the wire revision SMG's direct lane drives** (the
protocol
#2668–#2671 and #2674 described on the Python loop, which #2603
superseded):
- the ready response declares `request_types`, `positional_layouts`, the
disaggregation role, a prefill or encode server's bootstrap address, and
the checkpoint facts a frontend computes MRoPE positions from;
- CONTROL takes control calls `[call_id, method, args]`, answered with
one
`ControlReplySlim` each: `flush_cache`, `start_profile` and
`stop_profile`, and the RL and weight operations, whose argument is
the JSON body of the SGLang-compatible RL route of the same name;
- an EPD encode server's first rank dials the frontend and takes ENCODE
(0x03) frames (the request channel #2682 had it bind is gone);
- each rank's HELLO says how many engines dial as one group
(`engine_count`).
2. **feat(cli): serve through SMG's direct ZMQ lane**: `ts serve` runs
SMG's
gateway in front of the headless engine; the in-engine RL control app
goes.
3. **feat(runtime): remove AsyncLLM and the Python frontend**:
`AsyncLLM`, the
Python `Engine` and `LLM` API, the frontend-only flags and metrics, and
the SMG gRPC servicer dependencies. Tests and tools drive a headless
engine with `WireDriver`. A JSON schema on a reasoning model still waits
for the reasoning block, now in the host's ingress. Follower nodes keep
#1921's guarantee: their ranks die with them.
4. **feat(cli): serve disaggregated and multi-node deployments on SMG's
lane**: `ts serve` fronts an attention-DP engine whose replica leaders
sit
on other nodes through a `tcp://` worker on `--dist-init-addr`'s host;
PD and EPD run as headless engines behind `smg launch`
(`docs/serving/disaggregation.md`); the 7 CI jobs the removal had to
drop
come back on that recipe.
5. **fix(engine): refuse control operations an engine never answers**:
review
fixes and the stale-reference sweep.
## Dependency on SMG
The lane features this relies on (PD and EPD and MRoPE on the lane,
`tcp://` workers, control and RL calls, the declared engine group) are
in
SMG's pull request 4649 (its first part, the logprob columns, landed as
SMG's pull request 4630). Until it is released as `tokenspeed-smg` and
the
pin in `python/pyproject.toml` is bumped (a follow-up commit here), the
CI
jobs that need them cannot pass: the restored PD and EPD and multi-node
jobs, and `test_qwen35_vlm_e2e` (Qwen3.5 images through `ts serve`,
which
the pinned gateway refuses on the lane). Aggregated text serving works
with
the current pin.
## Validation (H20)
- Rust: workspace tests, clippy, fmt; Python: CLI and CI-system tests,
the
runtime-1gpu, runtime-2gpu and prefix-cache suites (failures match
`main`
on this host, models it does not cache).
- With the SMG changes: aggregated greedy completions token-identical to
before; 1P1D token-identical to aggregated (also with a DP2 MoE
prefill);
1E1P1D image answers correct, embeddings byte-identical between the
encode
server and prefill; gateway MRoPE positions equal
`compute_mrope_positions`; two-node `ts serve` with both ranks serving;
the
CI PD and EPD launchers run end to end; flush, profile, pause and
continue, release and resume and a disk refit through the control calls.
- With the current pin: aggregated `ts serve` works.
Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
---------
Signed-off-by: FC-Li <robert_lexis@163.com>
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
Co-authored-by: LightSeek Foundation <243258330+lightseek-bot@users.noreply.github.com>
Gateway-selected prefill and decode ranks currently get discarded or
ignored by TokenSpeed. Preserve those pins through validation and
dispatch, while checking at ingress that the prefill pin agrees with the
bootstrap room used to locate its KV cache: `bootstrap_room % dp_size`
must match the pinned prefill rank, and a conflicting prefill pin is
rejected. The decode rank may differ from the room residue, so prefill
and decode can select independent ranks safely. Out-of-range pins are a
caller error on attention-DP engines in colocated, prefill, and decode
modes alike; engines without attention DP still drop the pin, and a
malformed pin that reaches the dispatch loop falls back to the
configured policy rather than raising. Unpinned requests are unaffected:
the configured dispatch policy applies, and `round_robin` continues to
select the room residue in prefill and decode mode.
Admit the full usable request length: `max_req_len` is no longer one
token short of the context bound, and the generation budget is
`max_req_len - prompt_length`. Input admission already leaves room for
the first decode and verify window, so that input reserve is not
subtracted again from the remaining output budget; the scheduler design
doc now records the rule.
Treat the dsv41 selection widths as runtime data in `_finish_selection`
and `_write_selection` — moved out of `tl.constexpr` and into
`do_not_specialize` — so only their power-of-two tiles specialize and
changing a width between calls no longer forces a Triton recompile. New
tests sweep widths and assert the compiled kernels are reused.
Bump the bundled SMG packages to the matching post20261023 builds that
carry the gateway-side rank and capacity fixes, while preserving
TokenSpeed's engine metrics flags during the upgrade.
Keep the gateway's native load-snapshot contract after the Rust
control-plane migration. Without it, load polling falls back to
unavailable legacy page geometry and removes healthy prefill and decode
workers from routing. Idle reports keep capacity available before the
first request and expire when a rank stops reporting. The EPD launcher
also selects the pinned servicer’s supported `submit_encode` path
because its off-loop path still requires the removed engine-core client;
input parsing therefore runs on the event loop.
Validation on the updated head: GB200 `ut-runtime-qwen35-epd-1e1p2d`
passed, 292 Rust tests passed, 24 Python wire-conformance tests passed,
and clippy, rustfmt, and pre-commit passed.
---------
Signed-off-by: Enwei Zhu <21126786+syuoni@users.noreply.github.com>
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
Co-authored-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
Require the release that declares and locates the CUDA runtime for
native Mooncake loading. Keep the CUDA 12.9 wheel pin aligned with the
runtime minimum.
The experimental Hopper recipe still combines Torch's CUDA 12.6 runtime
with CUDA 12.9 Mooncake binaries, which require `cudaMemcpyBatchAsync`.
That existing incompatibility needs a separate fix; this version bump
does not resolve it.
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
EPD load polling rejected healthy workers because native allocator
reports lost total capacity and the adapter required legacy token-page
geometry. Encoder ingest also called a removed engine client, preventing
image requests from reaching the encode worker.
The compatible servicer preserves native occupancy and uses the
supported encoder submission API while retaining the existing gateway
and proto versions. Addresses the EPD CI failures seen in #2701.
---------
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
Use the smaller Transfer Engine and Store release that fits PyPI's file
limit. Keep the CUDA 12.9 constraint aligned with the runtime
requirement so installation remains satisfiable. The live-master
workflow already reads that requirement.
Validation: pre-commit, five Rust live-master tests, and 69 Python L3
tests passed.
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
## Summary
Every engine rank now runs the control plane in Rust, as [RFC
0002](docs/rfcs/0002-rust-control-plane.md) proposes. A rank is one
`ts-host` process: the scheduling loop, request state and output
processing, the per-round agreements among ranks, control operations, PD
and EPD transfers with their planning, the L3 storage tier, grammars,
the expert rebalance, metrics and KV events run in Rust, and the
embedded interpreter runs only the data plane (`DeviceHandle`, models,
kernels) on the host's forward thread. An EPD encode server's ranks are
`ts-host` processes too, in an encode mode whose data plane runs only
the vision tower. The Python event loop and its hooks are deleted in the
same change; there is no second path. `docs/design/event-loop.md` is
rewritten against the Rust loop.
The branch is rebased onto current `main`; the control-plane changes
`main` made meanwhile are ported to the Rust host in their own commit
(asynchronous L3 #2483, the grammar host node #2542, the EAGLE-4 settle
#2547, #2596, #2605).
Commits:
1. `feat(engine): run every engine rank on the Rust control plane (RFC
0002)`
2. `fix(engine): cancel grammar-queued requests on a drain, drop
finished aborts`
3. `chore(engine): port main's control-plane changes to the Rust host`
4. `refactor(engine): fold the pump thread into the forward thread`: one
forward thread runs the data plane's device work; the control thread
runs the completion queries itself, taking the GIL for the call (a
commit waits on the torch copy event, which releases it), with no native
event waits.
5. `feat(engine): run the L3 storage tier in the Rust host`: the L3
executor, its stores (Mooncake through the store's C ABI, an in-memory
store for tests) and its metrics are the new `ts-l3`, so neither the
per-round storage poll nor the I/O workers take the GIL.
6. `fix(engine): answer every refused request as a client error`: every
ingress refusal finishes with status 400, so a wire client can tell the
request's own error from an engine failure.
7. `fix(engine): close the Rust control plane review's findings`: PD
rooms no request claimed expire instead of blocking memory releases, a
landing without its first token fails its room, a drain cancels the EPD
requests still receiving, frozen rounds plan their cache work without
L3, a closed frontend input stops the engine, and the L3 reports ride
the round's relay exchange.
8. `feat(engine): port the PD transfer planner to ts-pd`: the cache
transfer contract, block manifests, routes between unequal Prefill and
Decode rank sets (head partitions, pipeline stages, KVP owner filters)
and copy planning, checked against a fixture of every call the Python
planner's tests made.
9. `feat(engine): plan PD transfers in the host, serve the bootstrap
from Rust`: the PD peer's threads no longer call into Python. The
scheduler facade exposes a batch's transfer columns and block tables,
the forward thread stages each plan's remote stream for the peer,
layerwise chunks are armed in Rust, and the bootstrap server is
`ts-pd`'s.
10. `feat(engine): receive EPD embeddings in the host`: the prefill
node's embedding receiver is `ts-pd`'s (encode-rank handshakes, receive
slots, the agreement on landed embeddings); the data plane keeps the
receive pools' memory, the publish copies and the row-shard reassembly.
11. `feat(engine): run EPD encode ranks in the host`: `ts-control`'s
encode loop relays, batches and leases send-ring slots, rank-identically
across the attention-TP group, and `ts-pd`'s sender writes the
embeddings; the data plane keeps the vision tower, the embedding cache
and the ring copies.
## What changes
**`tokenspeed-engine/`** (Cargo workspace):
| Crate | Role |
| --- | --- |
| `ts-wire` | The engine IPC schema and its msgpack codec, checked byte
for byte against fixtures the Python encoder writes |
| `ts-client` | A frontend's connection to the engines: handshake,
routing across attention-DP ranks, output streams, aborts, control
operations |
| `ts-py` | `tokenspeed_engine._native`: `ts-client` for the Python
frontend, the launcher's bootstrap server
(`tokenspeed_engine.BootstrapServer`), and the L3 executor for tests
(`tokenspeed_engine.L3Executor`) |
| `ts-collective` | CPU collectives among a rank's peers over a TCP mesh
|
| `ts-scheduler` | The C++ scheduler compiled into the binary, with a
`cxx` facade; its nanobind module is a built-in of the embedded
interpreter |
| `ts-control` | The loop and its subsystems: ingress, output commit,
cache-op acknowledgment, the L3 agreement, pause and memory release, the
same-round gate for weight operations, grammars, EPLB, KV events, PD
bookkeeping, EPD staging; and an EPD encode rank's loop |
| `ts-grammar` | Grammar compilation and matchers on xgrammar's C++
library |
| `ts-metrics` | Prometheus multiprocess files written directly, and the
events the node's plugin relay runs output plugins on |
| `ts-mooncake` / `ts-pd` | The Mooncake transfer engine and store
client through their C APIs; the PD transfer peer with its planning
(routes, block manifests, layerwise chunks, copies); the bootstrap
server; the EPD embedding receiver and sender |
| `ts-l3` | The L3 storage tier's Host-only executor: object naming, the
Host pool's layout and KV-parallel ownership, bounded queues and
workers, backend health, the stores |
| `ts-host` | The rank binary: an engine rank, or an EPD encode rank |
**Python.** Deleted: the event loop and its hooks, the request handler,
the generation output processor, the data-parallel controller, the
engine core client and pickle IPC, the Python headless msgpack
transport, the Python PD transfer executors and Mooncake
sender/receiver, the PD transfer planner (`pd/transfer_plan.py`,
`pd/mooncake/`, the manifest half of `pd/cache_protocol.py`) and the
aiohttp bootstrap server, the grammar manager and xgrammar backend, the
EPD prefill hooks and embedding receive job, the EPD encode loop,
worker, executor and scheduler with their Mooncake manager and sender
(`pd/base` with them), the Python L3 executor and its stores, and the
control-plane tests that covered them (their behaviour is covered by
`ts-control`'s unit and serving tests, which run the real scheduler
against a stand-in device, by `ts-pd`'s and `ts-l3`'s tests, and by the
planning fixture). Kept: the data plane; for PD, the cache transfer
contract built at startup and the device fences a plan's remote stream
waits on (`pd/host_peer.py`); for EPD, the receive pools and their
publish (`epd/prefill_receive.py`) and an encode rank's vision tower,
embedding cache and send ring (`epd/encode_host.py`); the L3 namespace
identity and settings (`cache/l3/identity.py`, `factory.py`); and
`AsyncLLM` as the in-process frontend over `ts-py`.
`engine/rust_host.py` builds a rank inside the host.
**Launching.** Every launch path (`Engine`, `ts serve`, `ts serve
--headless`) starts its ranks through `start_rust_host`, an EPD encode
server too (its ranks bind the request channel the frontend pushes
encode requests to). `TOKENSPEED_HOST_BINARY` overrides the binary the
new `tokenspeed-engine` wheel installs. A rank keeps its
`tokenspeed::scheduler_tp…` process title, an encode rank its
`tokenspeed::encode_tp…`.
**Packaging and CI.** `tokenspeed-engine` is a setuptools package that
builds `_native` and `ts-host` with cargo. `python/pyproject.toml`
depends on it. The CI installers and the source-built Dockerfiles build
it from the checkout (installing a Rust toolchain when the runner has
none), the engine workflow builds the wheel, and engine changes trigger
the GPU workflows.
## Deviations from the RFC's Phase 4
- `AsyncLLM` stays, as the in-process frontend over `ts-py`:
tokenization, detokenization, stop strings, `n > 1` fan-out and the
`Engine` API stay in Python, and so does the Python encoding of requests
onto the wire.
- `ts serve` keeps its gRPC servicer, now over that `AsyncLLM`. SMG's
msgpack backend does not yet carry MRoPE multimodal inputs, EPD encode
handshakes, shared-memory features or top-k/prompt logprobs, which the
CI model jobs need. Moving `ts serve` onto SMG's msgpack mode, and
deleting the servicer, waits for SMG.
- The control thread waits on a launched forward's torch copy event
(vendor-neutral, releasing the GIL) instead of native event handles
through `tokenspeed-kernel` C entries.
- The L3 store client moves into the host instead of staying on the data
plane.
## Behaviour changes
- `--zmq-msgpack` is removed: every engine speaks the msgpack wire.
- PD needs a `tokenspeed-mooncake` build with the TokenSpeed C entry
points (`libtokenspeed_transfer_engine.so`), and the Mooncake L3 store
one that ships the store's C ABI (`libmooncake_store.so`); a companion
change to the packaging repository adds both. Until that wheel is
published, `TOKENSPEED_MOONCAKE_LIBRARY` and
`TOKENSPEED_MOONCAKE_STORE_LIBRARY` name local builds, and the CI jobs
that install the wheel the runtime requires and need either library
fail: the Mooncake L3 workflow's live tests and the PD and EPD serving
jobs.
- A grammar that does not compile, or timed out past its retries, aborts
its request with status 400, and a grammar unusable on one rank fails
its request alike on every rank.
- Every request the engine refuses at ingress (invalid sampling
parameters, logprobs it cannot compute, too many stop token ids, a
session id, a disaggregated engine's missing bootstrap) finishes with
status 400; before, only the stop token ids refusal carried it.
- An EPD prefill node receives embeddings into its receive pool only:
with `TOKENSPEED_EPD_RECV_POOL_SLOTS=0` every handshaked item fails, an
item larger than a slot fails with a message naming
`TOKENSPEED_EPD_RECV_POOL_SLOT_MB`, and an exhausted pool keeps the
request waiting within its deadline (before, these fell back to a buffer
registered per request). A deepstack model's deepstack rows share their
item's slot (its bytes split 1 : num_deepstack), so the pool stays
within the bytes the cache budget leaves out.
- An EPD encode rank allocates its send ring at startup (same size as
before, which it allocated on the first send) and batches the waiting
items in arrival order, those the embedding cache holds first (before,
sorted by request id). An item whose prefill ranks did not all ask
within the bootstrap timeout now fails toward the ones that asked,
instead of leaving them to their own timeout, and a request for an
already failed room is answered at once.
- The host's Mooncake engines start with `MC_USE_IPV6` when the local
address is IPv6, as the Python engine did. The PD and EPD messages and
the bootstrap routes are unchanged.
## Validation
- `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings` and
`cargo test` pass for the whole workspace; the `ts-pd` transfer tests
pass over RDMA, and `ts-l3`'s live tests (round trips, objects outliving
their writer, owner relocation, tenant isolation, recovery after a
master restart) against a local master, with a local Mooncake build.
- `pytest` over `test/` (without the distributed and model e2e files):
the failures that remain also fail on `main` here (kernels this Hopper
node lacks, checkpoints and tokenizers not cached offline) or only in
the full run's order (log-capture tests that pass alone). The L3 Python
tests (scheduler tail round trips through the in-memory and live stores,
the settings factory, the GPU D2H/PUT/GET/H2D byte tests including
native Mooncake over TCP and RDMA, and the two-GPU KV-parallel owner
relocation over RDMA) pass on the Rust executor.
- Parity with `main`'s Python control plane on one 8-GPU Hopper node,
Qwen3-0.6B-Base, headless over the msgpack wire, 27 mixed requests
(sampling, stop tokens, prefix hits, chunked prefill): identical tokens,
finish reasons and cached-token counts in each of single GPU, TP2,
attention DP2, DUMMY speculation (TP1 and TP2), forced retraction, L3
with the in-memory store, and L3 with a Mooncake store over RDMA (single
GPU, and TP2 at concurrency 27).
- L3 across a restart: a fresh engine (empty L1/L2) restores a
2048-token prefix from Mooncake and continues exactly as a device prefix
hit does, single GPU and TP2; a flush deletes the namespace and a weight
update moves later pages to the new version's namespace; the L3 metrics
are exported.
- PD 1P1D (Qwen3-0.6B-Base, both roles on the Rust host), concurrency 1:
every greedy request is identical to the aggregated run (sampled
requests draw from a different stream across the two roles).
- PD planning: the Rust planner gives every call the Python planner's
test suite made the same answer or refusal (the recorded fixture). PD
1P1D on GPU (Qwen3-0.6B-Base) is token-identical to the branch before
the planner moved, for TP 1→1 (concurrency 1 and 8, layerwise and full
sends), 2→1, 1→2 and 2→2 (concurrency 1; at 8 the earlier build varies
run to run by itself).
- EPD: the Rust sender and receiver pass live RDMA tests together (one
prefill rank, two row-sharded ranks, a failed room, an incomplete
fanout). On GPU, Qwen3.5-0.8B behind SMG's EPD gateway, in 1E1P1D,
encode TP2 with prefill TP2, and encode TP1 with a row-sharded prefill
TP2, 15 sequential and concurrent requests (18 images, with two-image
requests and embedding-cache hits): every image's embedding reached
every prefill rank byte for byte as the encode rank computed it; the new
receiver also served the Python encode node unchanged.
- Earlier on this branch, before the rebase: `ts serve` completions and
chat matched `main`, each subsystem was checked against the Python loop
(also KV and context parallelism, layerwise PD, EPLB, grammars,
multimodal inputs, KV events, control operations and logprobs), and
DeepSeek-V4.1-Flash PD 1P1D (TP4+TP4, DSpark) served coherent text with
the same run-to-run variation as `main`.
- Seen on `main` too, not changed here: an idle attention-DP rank of a
dense model crashes in its zero-row forward (`silu_and_mul`), which L3's
pre-admission prefetch makes easy to hit with DP2.
## Known gaps
- PyPI wheels for `tokenspeed-engine` are not published yet; `ts-host`
links the libpython of the interpreter that builds it, so portable
wheels need a release recipe of their own. The release Dockerfile
installs published packages and needs that release first.
- Heterogeneous-TP PD sends a destination-contiguous, source-strided
fragment row by row; the Python sender packed it on the GPU first.
- Not run on GPU here: pipeline-parallel serving, the capturable grammar
path (needs a newer host compiler), request token history (needs an
out-of-tree model) and `--emulate-rank-zero` (AMD only). Their
control-plane paths are covered by the serving tests.
- SMG's `--servicer-impl rust` launcher imports the deleted Python
launch internals and needs an SMG update.
- SMG's encode servicer ingests requests off its event loop by default
through the deleted engine core client; until SMG submits through
`AsyncLLM.submit_encode` there as well, run it with
`EPD_INGEST_OFFLOOP=0`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Signed-off-by: FC-Li <robert_lexis@163.com>
Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
## Summary
Bump xgrammar from 0.2.3 to 0.2.8. With 0.2.3, `excludes` on the JSON
content of a structural tag is ignored without an error, so a tag that
keeps a marker out of JSON values still accepts it. 0.2.8 enforces it.
The reasoning tags of 0.2.8 also expect the prompt to open `<think>`, so
this PR makes the `json_schema` reasoning wrap pick its mode from the
prompt. A model that opens `<think>` itself, such as a hybrid Qwen3
model with thinking on, keeps working. It also gives the matcher the
model's end-of-sequence ids, so a grammar ends on every id the engine
stops on.
### Problem
- A structural tag can keep a string out of JSON values with `excludes`
on its `json_schema` content, for example a tool call's end marker
inside its arguments. xgrammar 0.2.3 has no such field and ignores it
without an error. A `<tool_call>` tag whose JSON excludes `</tool_call>`
accepts `{"query": "a</tool_call>b"}`.
- 0.2.3 also misses an `any_text` exclusion when the excluded string
comes right after text that started like the tag's end. With content
that excludes `</arg>` and the end `"\n</arg>\n"`, it accepts
`<arg>Paris\n</arg>zzz\n</arg>\n`.
- 0.2.4 to 0.2.8 fix both. Their release notes also list fixes for
`tool_choice="required"` tags that did not terminate, JSON `multipleOf`
and `prefixItems`, carriage-return whitespace, Unicode and negated
character classes, and inputs that crashed the process instead of
raising an error.
- In 0.2.8, the builtin reasoning tags behind TokenSpeed's `json_schema`
wrap for `--reasoning-parser qwen3`, `qwen3_thinking`, `deepseek_r1`,
`deepseek_v31`, `deepseek_v41` and `glm45` refuse `<think>` and
`</think>` inside the reasoning. The wrap always used the mode that
expects the prompt to open `<think>`. When the model opens it, 0.2.8
refuses its first token, where 0.2.3 took `<think>` as reasoning text.
This hits `tokenspeed serve Qwen/Qwen3-30B-A3B --reasoning-parser qwen3`
with thinking on, and DeepSeek-R1-0528, whose template does not open
`<think>`.
- With thinking off, the prompt closes the block and the model writes
only the answer. The wrap still waited for `</think>`, so the answer
could not end. This fails on 0.2.3 too.
- The backend built `TokenizerInfo` without stop ids, so the matcher
ended a grammar only on the tokenizer's own EOS. A model whose
generation config lists more end ids, for example a separate end id for
tool calls, stops on each of them, but the matcher read those ids as
text. A grammar could not end on them, and could not refuse them where
it must not end.
### Solution
- Pin `xgrammar==0.2.8`. In 0.2.8, `excludes` on `json_schema` content
applies to strings without `pattern` or `format`. On those strings it
drops `minLength` and `maxLength`, with a warning.
- Every xgrammar call in TokenSpeed keeps its arguments:
`TokenizerInfo.from_huggingface`, `GrammarCompiler` and its `compile_*`
calls (including the legacy `(tags, triggers)` form), `GrammarMatcher`,
`allocate_token_bitmask`, `apply_token_bitmask_inplace`,
`get_builtin_structural_tag` and the `xgrammar.structural_tag` formats.
The new parameters are keyword arguments with defaults, and
`reasoning=True` still works as an alias of `"enabled"`.
- Packaging: 0.2.8 needs `apache-tvm-ffi>=0.1.11`, and the kernel
package pins `0.1.13.post3`. It needs `transformers>=4.38.0` with no
upper bound. 0.2.4 and 0.2.5 required `transformers<5`, which TokenSpeed
cannot use. Like 0.2.3, it has Linux wheels for x86_64 and aarch64,
CPython 3.9 to 3.14, which covers the CUDA, ROCm and NPU installs. The
wheels no longer ship the static library and C++ headers (44 MB to 1.2
MB), which TokenSpeed does not use.
- Behavior changes for requests that work today, checked on CPU:
- `json_schema` accepts a carriage return as whitespace when any
whitespace is allowed (the default).
- Integer `multipleOf` is enforced: `7` no longer matches `{"type":
"integer", "multipleOf": 3}`.
- Regex: `\S` accepts `[`. Negated classes follow UTF-8, so `\S` and
`[^\s]` no longer match a no-break space. Negated classes and JSON
strings no longer allow bytes that cannot occur in UTF-8.
- A regex that contains NUL, and `excludes` on `json_schema` content
that is not a list, are refused as invalid grammars (HTTP 400).
- `TokenizerInfo.from_huggingface` now checks the vocabulary type
against the vocabulary itself. Five public tokenizers give the same
result as before.
- On NPU, xgrammar applies the mask with its torch kernel instead of
`torch.compile`.
- The `json_schema` reasoning wrap now picks xgrammar's reasoning mode
from the prompt token ids. If the last reasoning marker in the prompt is
`<think>`, the reply continues that block, and the wrap keeps
`"enabled"` with the same grammar as before. Otherwise it uses `"auto"`,
which accepts a complete `<think>...</think>` block or a direct answer.
A closed block cannot tell thinking off from the reasoning of an earlier
turn, which the Qwen3 template keeps in a tool-call history, so it also
gets `"auto"`.
- The markers come from xgrammar's builtin tag, and their token ids from
the tokenizer, once at startup. If they are not single tokens, or the
request has no token ids, the wrap keeps `"enabled"`. No model names are
checked.
- The gRPC servicer calls the wrap while it converts sampling params,
without the prompt. The wrap now returns `None` there, so the servicer
keeps `json_schema`, and `InputProcessor` wraps it with the prompt. Both
paths give the same grammar.
- The rule is the same for every mapped parser. For `kimi`, `kimi_k25`
and `minimax`, whose `"enabled"` tags still accept `<think>`, a prompt
that does not open the block now also allows a direct answer, and the
reasoning must start with `<think>`.
- `GrammarManager` passes the model's end-of-sequence ids
(`ModelConfig.hf_eos_token_id`, from `config.json` and
`generation_config.json`) to the backend. The backend adds the
tokenizer's own EOS and its `additional_stop_token_ids`, and builds
`TokenizerInfo` with them as `stop_token_ids`. The matcher then takes
each of these ids as the end of a grammar that may end there, and
refuses it anywhere else. With no config ids, `TokenizerInfo` is built
as before.
- No structural tag that TokenSpeed or the gateway builds today needs
one of these ids as text (checked below). xgrammar's builtin Harmony
tag, which TokenSpeed does not use, writes `<|call|>` and `<|return|>`
as text and would need endings on the stop ids before it is used.
### Performance
CPU, one process, the Qwen3 tokenizer (151,936 tokens). Cold compile
through `XGrammarGrammarBackend` with the cache cleared before each
compile, median of 15 compiles, two runs per version. Size is
`CompiledGrammar.memory_size_bytes`. Mask fill is the median over a walk
of up to 64 tokens.
| Grammar | Compile 0.2.3 | Compile 0.2.8 | Size 0.2.3 | Size 0.2.8 |
Mask fill 0.2.3 | Mask fill 0.2.8 |
|---|---|---|---|---|---|---|
| Any JSON | 11.7 ms | 10.2 ms | 170 KiB | 144 KiB | 30.6 us | 28.9 us |
| Object, 3 fields | 11.6 ms | 10.1 ms | 126 KiB | 119 KiB | 27.9 us |
27.3 us |
| Nested order object | 12.7 ms | 10.8 ms | 721 KiB | 274 KiB | 28.0 us
| 26.9 us |
| `$ref` and `anyOf` | 11.8 ms | 10.2 ms | 207 KiB | 166 KiB | 3.5 us |
4.2 us |
| Object, 40 fields | 13.0 ms | 10.9 ms | 1,359 KiB | 507 KiB | 38.3 us
| 36.1 us |
| String formats and a pattern | 177.8 ms | 146.8 ms | 4,271 KiB | 3,542
KiB | 3.2 us | 3.6 us |
| Regex (date-time) | 0.44 ms | 0.39 ms | 9.4 KiB | 3.6 KiB | 3.3 us |
3.6 us |
| EBNF (arithmetic) | 0.40 ms | 0.39 ms | 6.7 KiB | 4.8 KiB | 3.3 us |
3.4 us |
| Qwen3 tool-call tags, 3 tools | 17.9 ms | 15.3 ms | 1,509 KiB | 523
KiB | 7.3 us | 7.3 us |
| Qwen3 reasoning wrap of the nested object | 14.7 ms | 14.3 ms | 824
KiB | 284 KiB | 6.0 us | 6.3 us |
| `<tool_call>` tag with `excludes` (ignored on 0.2.3) | 12.9 ms | 48.6
ms | 768 KiB | 584 KiB | 27.7 us | 41.9 us |
Reasoning wrap on 0.2.8, CPU, two runs. The prompt scan stops at the
last marker, so it takes 0.2 to 0.3 us when the prompt ends with
`<think>` or closes the block near its end. A prompt with no marker is
read to the start: 17 us per 1K tokens, 2.2 ms at 128K tokens and 17.5
ms at 1M. The `"auto"` wrap of the nested order object compiles like the
`"enabled"` one:
| Wrap of the nested order object | Compile | Size | Mask fill |
|---|---|---|---|
| Qwen3, `"enabled"` | 14.4-14.7 ms | 284 KiB | 6.3 us |
| Qwen3, `"auto"` | 14.4-15.0 ms | 286 KiB | 6.2 us |
| DeepSeek-R1, `"enabled"` | 14.1-14.3 ms | 549 KiB | 4.7 us |
| DeepSeek-R1, `"auto"` | 14.0-14.3 ms | 551 KiB | 4.4-4.5 us |
Stop ids: `TokenizerInfo` is built once at startup. Compile time over 70
structural tags changes by +0.1%, which is noise. The mask fill code is
unchanged.
## Test Plan
- [x] `<tool_call>` tag with `excludes: ["</tool_call>"]` on its JSON
content: 0.2.3 accepts `{"query": "a</tool_call>b"}`, 0.2.8 refuses it.
Through `XGrammarGrammarBackend` with the Qwen3 tokenizer, the mask
inside the JSON string allows the `</tool_call>` token on 0.2.3 and not
on 0.2.8.
- [x] Tag whose `any_text` content excludes `</arg>` and whose end is
`"\n</arg>\n"`: 0.2.3 accepts `<arg>Paris\n</arg>zzz\n</arg>\n`, 0.2.8
refuses it.
- [x] Limits of `excludes` on 0.2.8: in the `<tool_call>` tag, a string
with `pattern: ".*"` still accepts `a</tool_call>b`, and a string with
`minLength: 5` accepts `"ab"`.
- [x] CPU, with each version: the 23 test files that mention grammar,
structural tags or response formats. Before the wrap change, 501 passed,
88 skipped and the same 16 failures on both in this CPU-only setup; no
test changes its outcome. Only `test_reasoning_structural_tag` calls
xgrammar. With the wrap change on 0.2.8, 524 passed (23 new tests) with
the same 16 failures, and every earlier test keeps its outcome.
- [x] `XGrammarGrammarBackend` with the Qwen3 tokenizer, each version:
20 seeded random walks each over a JSON schema, any JSON, a regex, an
EBNF, the `<tool_call>` tag, the Qwen3 tool-call tags (`auto` and
`required`) and the Qwen3 reasoning wrap. Every token the mask allows is
accepted, `rollback` and `copy()` give the same masks, and the applied
mask leaves exactly the allowed logits.
- [x] Malformed structural tags, JSON schemas, regexes and EBNF give the
same result on both versions, except the two new refusals above.
- [x] `TokenizerInfo` for Qwen3-4B-Instruct-2507,
Qwen3-Next-80B-A3B-Instruct, gpt-oss-20b, TinyLlama-1.1B-Chat and
LLaVA-1.5-7B: the same vocabulary type, prefix space, stop and special
tokens and decoded vocabulary on both versions.
- [x] New tests in `test_reasoning_structural_tag.py`, through
`InputProcessor.tokenize_one_request`, with prompts from public chat
templates. Qwen3-30B-A3B accepts a reply that opens `<think>` with
thinking on, and a plain JSON answer with thinking off.
Qwen3-4B-Thinking-2507 and DeepSeek-V3.1 with thinking on, whose prompts
open `<think>`, accept a reply that continues the block and refuse a
bare answer, as before. DeepSeek-R1-0528 accepts a reply that opens
`<think>`, and DeepSeek-V3.1 with thinking off a plain answer. With
GPT-2's tokenizer, where `<think>` is several tokens, the wrap keeps the
earlier mode. Every mapped parser finds its markers in xgrammar's tag.
27 passed on 0.2.8. Forcing the earlier mode fails 4 of them, and
forcing `"auto"` fails 3.
- [x] Token level, through `InputProcessor` and
`XGrammarGrammarBackend`: 8 prompt styles from these chat templates,
also a Qwen3 tool-call history and Qwen3-4B-Thinking-2507 under `qwen3`,
with 10 replies each that end with the EOS token. The reply each style
is for is accepted in 6 of 8 styles on 0.2.3, 3 of 8 on 0.2.8 without
the wrap change, and 8 of 8 with it. Every style that 0.2.3 handled is
still accepted; the 2 new ones are thinking off. Wrong JSON, a missing
answer and trailing text are refused in every setup.
- [x] Token level for the other mapped parsers, the same way: the public
templates or encoders of GLM-4.5, GLM-4.7, GLM-5, Kimi-K2.5 (`kimi_k25`
and `kimi`), MiniMax-M2 and M2.5, the original DeepSeek-R1, and
DeepSeek-V3.2 and V4-Flash (`deepseek_v31` and `deepseek_v41`), with
thinking on and off where the template has the option. The reply each of
23 prompt styles is for is accepted in 14 on 0.2.3, 14 on 0.2.8 without
the wrap change, and 21 with it. The 7 new ones are thinking off or chat
mode. The 2 left are GLM-4.5, which writes a newline before `<think>`
and before the answer; no setup accepts them. Wrong JSON and trailing
text are refused in every setup.
- [x] When the prompt opens `<think>`, the grammar is byte-identical to
the one before the wrap change. The other differences from 0.2.3:
`<think>` inside an open block is refused (the 0.2.8 tags), and when the
prompt did not open the block, the reasoning must start with `<think>`.
- [x] The pinned gRPC servicer gives the same grammar as a direct
`json_schema` request in every setup above.
- [x] Stop ids: `test_grammar_stop_tokens.py` (4 new tests) and
`test_grammar_manager_headless.py`. A second end id ends a grammar where
it may end and is refused before; config ids that leave out the
tokenizer's EOS and extra stop ids still end on both; without stop ids a
second id is read as text. The 23 grammar test files plus
`test_grammar_stop_tokens.py`: 562 passed, with the same 10 CPU-only
failures as before.
- [x] Stop ids against today's grammars: 19 TokenSpeed structural-tag
variants, 254 gateway payloads and 27 legacy parser payloads, each with
its model's real stop ids from `config.json`, `generation_config.json`
and the tokenizer. None needs a stop id as text.
- [ ] GPU: the grammar GPU tests and a serving run with `json_schema`,
`regex`, `ebnf` and `structural_tag` requests.
---------
Signed-off-by: yechank <161688079+yechank-nvidia@users.noreply.github.com>