Files
tokenspeed/test/runtime/test_cuda_stack.py
lipanpan03andFC-Li cff8263007 fix(runtime): release persistent buffers during memory-saver sleep (#3407)
## Summary

Memory-saver sleep releases model weights and KV pages, but persistent
attention metadata and shared scratch buffers can remain allocated. Put
attention/backend initialization, runtime inputs and history,
decode/prefill graph metadata, and workspace growth in a separate
CPU-backed pool under the existing `weights` tag. Sleep/wake preserves
their contents and virtual addresses, including when model parameters
use `discard`.

- Resolve owner-specific `named_region` aliases (`executor_inputs`,
`runtime_states`, `attention_state`, `workspace`) to the shared
CPU-backed pool. Nested aliases reuse that pool across adapter
instances. The executor owns the adapter and passes it to prefill
graphs; neither depends on the KV arena's adapter.
- Include already-created split NCCL communicators before their first
collective, without initializing unused groups.
- Drain device work before suspend, clear allocator caches, and restore
the previous CUDA stack limit before resuming communication. Skip NVIDIA
driver stack operations on ROCm. Clear cuBLAS workspaces only in CUDA
eager mode; retain graph-referenced workspaces.
- Coordinate NCCL-containing release and resume through the existing
attention-DP gates. A peer's completed KV release cannot authorize a
later NCCL release, and NCCL resume waits for every DP engine's request.
Ordinary memory regions retain their local resume behavior.
- Preserve explicitly supplied `NCCL_CUMEM_ENABLE` and
`CUDA_MODULE_LOADING` settings. Keep the existing communication backend
and worker lifecycle. No native NCCL or PyTorch changes.
- Update affected executor configurations and all prefill-graph
constructor fixtures, including capture-failure coverage, plus
memory-policy and event-loop documentation.

## Validation

- `cargo test --locked -p tokenspeed-control --lib --test serving`:
**167 unit tests and 63 serving tests passed**. These use the real C++
scheduler with scripted device/DP boundaries, including the two NCCL
transition regressions; they do not execute GPU collectives.
- Focused CPU runtime checks: **142 passed, 10 skipped**, plus 34
passing subtests. Covered prefill/drafter graph behavior, all 16
executor-capacity parametrizations, cache-state allocation, executor
rebind, CUDA/ROCm cleanup guards, named allocation regions, cached
split-communicator discovery, and stack restoration. The 10 skips
require CUDA.
- CPU harness limitation: real runtime classes, CPU metadata routines
and the built scheduler were used; unavailable GPU kernel/compiler and
profiling imports, GPU capacity queries, and optional vision/audio
dependencies were isolated. This is not CUDA allocation or ROCm
execution evidence.
- A broader `DeviceHandle` run reached an unchanged control-plane guard
test that fails on the local CPU-only PyTorch 2.9 build: CUDA factory
initialization raises before its dispatch guard. That case is not
counted as passing; the full runtime suite is not claimed to pass.
- `pre-commit run --all-files` and `cargo fmt --all --check`:
**passed**.
- `cargo clippy --locked -p tokenspeed-control --all-targets -- -D
warnings`: **passed**.
- Full distributed CUDA sleep/wake, physical-memory reclamation,
captured graph replay, and suspend/resume followed by the first
collective on a cached split communicator remain **pending GPU
validation**. Measure physical device memory rather than inferring
reclamation from retained virtual Tensor storage.

---------

Signed-off-by: lipanpan03 <41904587+lipanpan03@users.noreply.github.com>
Signed-off-by: FC-Li <robert_lexis@163.com>
Co-authored-by: FC-Li <robert_lexis@163.com>
2026-11-14 15:00:27 +08:00

74 lines
2.7 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.
"""Exercise stack-limit restoration without creating a CUDA context."""
from test.ci_system.ci_register import register_cuda_ci
import pytest
from tokenspeed.runtime.distributed import cuda_stack
register_cuda_ci(est_time=5, suite="runtime-1gpu")
class StackDriver:
def __init__(self, limit):
self.limit = limit
self.get_error = 0
self.set_error = 0
def cuCtxGetLimit(self, pointer, kind):
pointer._obj.value = self.limit
return self.get_error
def cuCtxSetLimit(self, kind, limit):
if not self.set_error:
self.limit = limit
return self.set_error
@pytest.mark.parametrize("limit", [0, 2048])
def test_stack_limit_is_restored_across_sleep_cycles(monkeypatch, limit):
driver = StackDriver(limit)
monkeypatch.setattr(cuda_stack, "_driver", lambda: driver)
for _ in range(2):
saved = cuda_stack.trim_cuda_stack()
assert saved == limit
assert driver.limit == 0
cuda_stack.restore_cuda_stack(saved)
assert driver.limit == limit
@pytest.mark.parametrize("operation", ["read", "trim", "restore"])
def test_stack_driver_failure_propagates(monkeypatch, operation):
driver = StackDriver(2048)
monkeypatch.setattr(cuda_stack, "_driver", lambda: driver)
if operation == "read":
driver.get_error = 201
else:
driver.set_error = 201
with pytest.raises(RuntimeError, match="CUresult 201"):
if operation == "restore":
cuda_stack.restore_cuda_stack(2048)
else:
cuda_stack.trim_cuda_stack()
assert driver.limit == 2048