Files
tokenspeed/test/runtime/test_executor_rebind.py
yanlonghuandyanlonghu 382da44551 feat(ascend): suspend and resume ACL graphs with torch-npu-memory-saver (#3667)
## 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>
2026-11-27 01:42:41 +08:00

359 lines
13 KiB
Python

# Copyright (c) 2026 LightSeek Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""The executor's rebind: what it captures, releases, republishes and rebuilds."""
from __future__ import annotations
import importlib
import os
import sys
from types import SimpleNamespace
from unittest.mock import Mock
# Executed as a script by run_ci_suite: the test dir must be importable.
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import pytest # noqa: E402
from ci_system.ci_register import register_cuda_ci # noqa: E402
register_cuda_ci(est_time=5, suite="runtime-1gpu")
from tokenspeed.runtime.execution import model_executor as module # noqa: E402
from tokenspeed.runtime.execution.drafter.base import BaseDrafter # noqa: E402
from tokenspeed.runtime.execution.model_executor import ModelExecutor # noqa: E402
from tokenspeed.runtime.utils.torch_memory_saver_adapter import ( # noqa: E402
TorchMemorySaverAdapter,
)
def _pool(tag, *, attn_kind="full_history"):
return SimpleNamespace(
arena=SimpleNamespace(
runtime_contract=SimpleNamespace(
tag=tag, group_specs=(SimpleNamespace(attn_kind=attn_kind),)
),
cache_group_specs=(f"{tag} spec",),
cache_group_page_counts={f"{tag} group": 3},
)
)
class _Holder:
"""A backend, drafter or context producer; logs what it is handed."""
cache_consumer_attn_kinds = ("full_history", "sliding_window")
def __init__(self, name, log, pool=None):
self.name, self.log, self.token_to_kv_pool = name, log, pool
self.draft_model_runner = SimpleNamespace(model="draft model")
def set_cache_pool(self, pool):
self.token_to_kv_pool = pool
self.log.append((self.name, "set_cache_pool", pool))
def configure_runtime(
self, *, cache_group_specs, cache_group_page_counts, request_slot_capacity=None
):
self.log.append(
(self.name, "configure", cache_group_specs, cache_group_page_counts)
)
def _executor(monkeypatch, log, *, with_draft: bool):
executor = ModelExecutor.__new__(ModelExecutor)
executor.device = "cuda"
executor.memory_saver_adapter = TorchMemorySaverAdapter.create(
enable=False, device="cpu"
)
executor.config = SimpleNamespace(
spec_algo=None,
enforce_eager=False,
pp_size=1,
max_req_pool_size=3,
state_checkpoint_in_forward=False,
)
executor.model_runner = SimpleNamespace(model="target model")
executor.attn_backend = _Holder("target", log)
executor.token_to_kv_pool = _pool("probe")
executor._cache_runtime_contract = "probe contract"
executor.input_buffers = "input buffers"
executor.sampling_backend = "sampling"
executor.runtime_states = "runtime states"
executor.grammar_runtime = None
executor._graph_support = SimpleNamespace(decode_graph=True, prefill_graph=True)
draft = _pool("probe draft") if with_draft else None
executor.draft_token_to_kv_pool = draft
executor.draft_attn_backend = with_draft and _Holder("draft", log) or None
executor.drafter = with_draft and _Holder("drafter", log, draft) or None
executor._draft_model_runner = (
with_draft and executor.drafter.draft_model_runner or None
)
executor.dspark_context_producer = (
with_draft and _Holder("producer", log, draft) or None
)
def owner(**kwargs):
log.append(("owner",))
return SimpleNamespace(kwargs=kwargs, **kwargs)
validate = module.validate_scheduler_config
monkeypatch.setattr(
module,
"validate_scheduler_config",
lambda **kw: log.append(("validate", kw["attn_backend"], kw["kv_pool"]))
or validate(**kw),
)
monkeypatch.setattr(
module,
"bind_cache_groups",
lambda model, pool: log.append(("bind", model, pool)),
)
monkeypatch.setattr(module, "ForwardStepRunner", owner)
monkeypatch.setattr(module, "PrefillGraph", owner)
executor._build_graph_owners()
log.clear()
return executor
@pytest.mark.parametrize("with_draft", [True, False])
def test_a_rebind_republishes_every_holder_onto_the_new_pools(monkeypatch, with_draft):
log = []
executor = _executor(monkeypatch, log, with_draft=with_draft)
target = _pool("real")
draft = _pool("real draft") if with_draft else None
# Nothing may latch the first publish: the probe is one rebind, not the last.
executor.set_cache_pool(_pool("first"), draft and _pool("first draft"))
log.clear()
executor.set_cache_pool(target, draft)
expected = [("validate", executor.attn_backend, target)]
if with_draft:
expected += [
("drafter", "set_cache_pool", draft),
("producer", "set_cache_pool", draft),
]
expected += [("target", "configure", ("real spec",), {"real group": 3})]
if with_draft:
expected += [
("draft", "configure", ("real draft spec",), {"real draft group": 3})
]
expected += [("bind", "target model", target)]
if with_draft:
expected += [("bind", "draft model", draft)]
# The backends took the pool when it was built; binding again drops their workspace.
assert log == expected + [("owner",), ("owner",)]
assert executor._cache_runtime_contract is target.arena.runtime_contract
assert executor.forward_step.token_to_kv_pool is target
assert executor.forward_step.draft_token_to_kv_pool is draft
assert executor.prefill_graph.token_to_kv_pool is target
# No holder of a pool is left on the replaced arena.
for name, value in vars(executor).items():
for held in (
value,
*(vars(value).values() if hasattr(value, "__dict__") else ()),
):
if getattr(held, "arena", None) is not None:
assert held is target or held is draft, name
def test_a_rebind_to_an_unconsumable_pool_fails_where_it_happens(monkeypatch):
executor = _executor(monkeypatch, [], with_draft=False)
with pytest.raises(RuntimeError, match="missing"):
executor.set_cache_pool(_pool("real", attn_kind="state"), None)
@pytest.mark.parametrize("spec_algo", ["DFLASH", "DSPARK"])
def test_a_block_drafter_is_rechecked_against_the_targets_new_pool(
monkeypatch, spec_algo
):
log = []
executor = _executor(monkeypatch, log, with_draft=True)
executor.config = SimpleNamespace(
spec_algo=spec_algo,
enforce_eager=False,
pp_size=1,
max_req_pool_size=3,
state_checkpoint_in_forward=False,
)
monkeypatch.setattr(
module, "check_block_drafter_storage", lambda m, p: log.append(("check", m, p))
)
target = _pool("real")
executor.set_cache_pool(target, _pool("real draft"))
assert [e for e in log if e[0] == "check"] == [("check", "draft model", target)]
def test_capture_hands_both_owners_the_entries_and_the_drafter_its_window(
monkeypatch,
):
seen = []
executor = ModelExecutor.__new__(ModelExecutor)
executor.device = "cuda"
executor.config = SimpleNamespace(enable_cudagraph_gc=False)
executor.forward_step = SimpleNamespace(
disable=False,
stream="stream",
capture=lambda *, entries, observer: seen.append(("decode", entries, observer)),
)
executor.prefill_graph = SimpleNamespace(
disable=False,
capture_buckets=[16],
capture=lambda wrapper, *, entries, observer: seen.append(
("prefill", entries, observer, wrapper)
),
)
executor.drafter = SimpleNamespace(
captures_prefill_graph=True,
capture_prefill_graph=lambda stream, window: seen.append(
("drafter", stream, window)
),
extend_graph_plan=lambda token_buckets: {},
)
monkeypatch.setattr(
module, "workspace_pool", lambda _d: SimpleNamespace(freeze=lambda: None)
)
observer = SimpleNamespace(measure=lambda series: f"window:{series}")
executor.capture_graphs(entries=3, observer=observer)
assert seen == [
("decode", 3, observer),
("prefill", 3, observer, executor.forward_step),
("drafter", "stream", "window:prefill:drafter"),
]
def test_graphless_ascend_startup_checks_model_and_kv_ownership(monkeypatch):
executor = ModelExecutor.__new__(ModelExecutor)
executor.device = "npu"
executor.config = SimpleNamespace(enable_memory_saver=True)
executor.forward_step = SimpleNamespace(disable=True, graphs={})
executor.prefill_graph = SimpleNamespace(disable=True)
saver = Mock()
executor.model_runner = SimpleNamespace(model="target", memory_saver_adapter=saver)
executor._draft_model_runner = SimpleNamespace(model="draft")
regions = {"arena": object()}
executor.token_to_kv_pool = SimpleNamespace(arena=SimpleNamespace(regions=regions))
monkeypatch.setattr(module, "workspace_pool", lambda _: Mock())
executor.capture_graphs(entries=None, observer=None)
saver.validate_startup.assert_called_once()
inventory = saver.validate_startup.call_args.kwargs
assert inventory["models"] == [("target", "target"), ("draft", "draft")]
assert inventory["kv_regions"] is regions
assert list(inventory["graphs"]) == []
def test_releasing_frees_both_owners_the_drafter_and_the_workspace(monkeypatch):
order = []
executor = ModelExecutor.__new__(ModelExecutor)
executor.device = "cuda"
executor.forward_step = SimpleNamespace(
release_graphs=lambda: order.append("decode")
)
executor.prefill_graph = SimpleNamespace(
release_graphs=lambda: order.append("prefill")
)
executor.drafter = SimpleNamespace(
release_prefill_graph=lambda: order.append("drafter"),
release_extend_graphs=lambda: order.append("drafter extend"),
release_round_graphs=lambda: order.append("drafter rounds"),
)
monkeypatch.setattr(
module,
"workspace_pool",
lambda device: SimpleNamespace(
unfreeze=lambda: order.append(("unfreeze", device))
),
)
monkeypatch.setattr(module.gc, "collect", lambda: order.append("collect"))
executor.release_graphs()
assert order == [
"decode",
"prefill",
"drafter",
"drafter extend",
"drafter rounds",
("unfreeze", "cuda"),
"collect",
]
def test_the_drafter_hooks_take_the_pool_and_drop_what_named_the_old_one(monkeypatch):
from tokenspeed.runtime.execution.drafter import _dflash_fused_kv
from tokenspeed.runtime.execution.drafter.dflash import DFlash
from tokenspeed.runtime.execution.dspark_context import DSparkContextProducer
base = BaseDrafter.__new__(BaseDrafter)
BaseDrafter.set_cache_pool(base, "real")
assert base.token_to_kv_pool == "real"
# DFlash pre-stacks raw KV views and caches their pointers module-wide.
monkeypatch.setitem(_dflash_fused_kv._cached_kv_ptrs, 1234, ("k", "v"))
dflash = DFlash.__new__(DFlash)
rebuilt = []
dflash._init_fused_kv_helper = lambda: rebuilt.append("fused_kv")
dflash._init_context_taps = lambda: rebuilt.append("context_taps")
dflash.set_cache_pool("real")
assert dflash.token_to_kv_pool == "real"
assert _dflash_fused_kv._cached_kv_ptrs == {}
assert rebuilt == ["fused_kv", "context_taps"]
# Only the last pipeline stage owns the draft context cache.
producer = DSparkContextProducer.__new__(DSparkContextProducer)
producer.token_to_kv_pool = _pool("probe draft")
producer.set_cache_pool(_pool("real draft"))
with pytest.raises(ValueError, match="ownership"):
producer.set_cache_pool(None)
def test_a_drafter_that_captures_a_prefill_graph_declares_and_releases_it():
for name in (
"deepseek_v41_dspark",
"dflash",
"dflash2",
"dspark",
"eagle",
"mtp",
):
importlib.import_module(f"tokenspeed.runtime.execution.drafter.{name}")
def _descendants(cls):
for sub in cls.__subclasses__():
yield sub
yield from _descendants(sub)
concrete = list(_descendants(BaseDrafter))
assert len(concrete) >= 6
hooks = {"capture_prefill_graph", "captures_prefill_graph", "release_prefill_graph"}
for cls in concrete:
assert hooks & set(vars(cls)) in (set(), hooks), cls.__name__
if __name__ == "__main__":
raise SystemExit(pytest.main([__file__, "-v"]))