Files
tokenspeed/test/runtime/test_host_sync.py
FC.Liandlongcat-ia-team 0dcb71840b ci: always arm the data-plane sync check and serve CI with it raising (#2860)
## Summary

The forward thread must not synchronize with the device on the per-round
path (`docs/design/event-loop.md`): a `.cpu()`, `.item()`, `.tolist()`,
boolean-mask index or pageable copy there waits for the step in flight
and degrades overlap scheduling to depth 0. The check that enforces this
(torch's sync-debug mode, armed in `enter_serving`) was off unless
`TOKENSPEED_DATA_PLANE_SYNC_DEBUG` was set. No CI task set it, although
the design doc said CI served with `error`, and `test_host_sync.py` was
not registered with any CI suite.

- **Always on.** Serving always arms the check.
`TOKENSPEED_DATA_PLANE_SYNC_DEBUG` only picks whether a report warns
(the default) or raises; any other value, the old `default` included, is
refused at startup.
- **CI raises.** `test/ci_system/pipeline.py` serves every
`server_smoke`, `eval`, and `perf` task with `error`, overriding a value
inherited from the runner. `validate_task` rejects a task or
`runner.env` that sets the variable.
- **Fixes for the violations found on CI paths:**
- A PD decode destination landed each remote prefill's speculative
candidates with `spec_candidates_ready[idx] = True`, which stages the
Python scalar through a pageable host tensor (a host sync per landed
request). It now uses `fill_`. Found by the survey below.
- `deepep_scatter` (DeepEP normal-mode MoE) uploaded the per-expert
block starts and counts from pageable memory. They now share one pinned,
non-blocking upload. Found by this PR's CI
(`eval-qwen3.5-35b-a3b-fp8-deepep-tp2dp2ep4-gsm8k`).
- `MultimodalRuntime.build_positions_override` uploaded a prefill
chunk's M-RoPE positions table, and a delta-only input's delta, from
pageable memory. The chunk, a strided slice of the table, is now
gathered into a contiguous pinned buffer and copied without blocking (a
strided pinned source still goes through a pageable temporary), and the
delta is read as a host scalar, as the decode path does. Found by this
PR's CI (`eval-qwen3.5-122b-a10b-nvfp4-epd-1e1p2d-ocr-bench`).
- GLM-5.3 KPool prefill plans uploaded about a dozen host-built index
lists, Qwen4-exp PLE ragged batch indices uploaded the request lengths,
MoonViT (Kimi-K2.5 vision) moved the image grid to the device only to
read it back on the host, and encoder CUDA graph replay padded
`cu_seqlens` from pageable memory. Found by this PR's CI (GLM-5.3 MTP on
B200 and MI35x, Qwen3.8-flash-next on MI35x, Kimi-K2.5 OCR). They now go
through a new helper, `host_to_device` (`utils/host_sync.py`):
contiguous pinned memory and a non-blocking copy, refused under graph
capture. The MoonViT grid stays on the host, as Qwen3.5 already keeps
it.
- `test_host_sync.py` and
`test/runtime/execution/test_multimodal_runtime.py` are registered in
`runtime-1gpu`; neither ran in CI before. The new
`test/runtime/test_kpool_prefill_plan.py` is registered with them.

## Survey (warn mode, before this change)

Served the main branch on 8×H20 with
`TOKENSPEED_DATA_PLANE_SYNC_DEBUG=warn` and a hook that reports every
distinct Python stack of a flagged sync. A positive control (one
injected `.tolist()` on the forward thread after arming) confirmed the
hook catches syncs inside the Rust host's embedded interpreter. Each run
sent greedy and sampled requests (temperature, top-p, top-k and min-p,
penalties, seed, stop strings, `n=2`, `ignore_eos`), output and prompt
logprobs, chunked-prefill prompts and their prefix-cache hits, streams,
client disconnects mid-stream, and a burst after idling.

| Config | Violations |
|---|---|
| Qwen3-0.6B, TP1 | 0 |
| Qwen3-30B-A3B, attention DP4 + EP4 | 0 |
| DeepSeek-V4.1-Flash, TP8 + EP | 0 |
| DeepSeek-V4.1-Flash, TP8 + EP, DSPARK, text | 0 |
| DeepSeek-V4.1-Flash, TP8 + EP, DSPARK, image requests | 4, all in the
vision tower |
| DeepSeek-V4.1-Flash, 1P1D (TP4 + EP4 each), DSPARK | 1 on decode,
every landed request (fixed here) |

The four vision-tower sites (`deepseek_v41_vision.py`: the RoPE table
and `cu_seqlens` uploads, the `types` upload, `block[types == 1] =
embeds`) run only on image prefill rounds, and no CI task sends images
to this model, so they are left for a follow-up; under the new default
they warn. Not covered by the survey: EAGLE3 and MTP speculation, the
Kimi and Qwen3.5 vision towers, and AMD paths. This PR's CI runs the
per-commit tasks for those with `error`.

## Test plan

- [x] `test/ci_system/test_pipeline.py` and `test_eval_configs.py`: 234
passed. The new sync-check tests fail without the pipeline change.
- [x] `test/runtime/test_host_sync.py`: 7 passed.
`test/runtime/test_runtime_states.py`: 13 passed; the new landing test
raises without the fix.
- [x] DeepSeek-V4.1-Flash 1P1D with DSPARK, this branch,
`TOKENSPEED_DATA_PLANE_SYNC_DEBUG=error`: every request served and no
sync raised (before the fix, warn mode reported the landing site on
every request).
- [x] `test/runtime/execution/test_multimodal_runtime.py`: 12 passed.
`tokenspeed-kernel/test/ops/moe/test_deepep_permute.py`: 17 passed. Each
new sync-debug test raises without its fix; the M-RoPE test also holds
the stream behind a long kernel and asserts the call returns before it
finishes, which fails with a strided pinned copy.
- [x] `host_to_device` tests (values, strided sources, no wait behind a
long kernel, capture refused), a KPool plan built on CUDA that matches
the host build without waiting, PLE ragged indices and `cu_seqlens`
padding under sync-debug error mode; each fails without its fix.
- [x] All per-commit model tests pass with `error` (B200, GB200, MI35x).
GB300 tests run nightly, so
`eval-deepseek-v4.1-flash-pd-1p1d-dspark-gsm8k-gb300-slurm` was
dispatched for this PR through Slurm Dispatch: passed, GSM8K 0.98.
- [x] `pre-commit run --all-files`.

Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>

---------

Signed-off-by: FC-Li <robert_lexis@163.com>
2026-10-31 15:45:32 -07:00

169 lines
6.4 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 data-plane host-sync guard: arming, reporting and explicit exemptions."""
from __future__ import annotations
import os
import sys
import pytest
import torch
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from ci_system.ci_register import register_cuda_ci # noqa: E402
register_cuda_ci(est_time=10, suite="runtime-1gpu")
from tokenspeed.runtime.execution import device as device_module # noqa: E402
from tokenspeed.runtime.utils.env import envs # noqa: E402
from tokenspeed.runtime.utils.host_sync import ( # noqa: E402
allow_host_sync,
host_to_device,
)
requires_cuda = pytest.mark.skipif(
not torch.cuda.is_available(), reason="requires CUDA"
)
@pytest.fixture
def sync_debug_off():
yield
if torch.cuda.is_available():
torch.cuda.set_sync_debug_mode(0)
@requires_cuda
def test_error_mode_rejects_the_hidden_syncs_and_passes_the_async_forms(sync_debug_off):
x = torch.arange(8, device="cuda")
flags = torch.ones(8, dtype=torch.bool, device="cuda")
slots = torch.tensor([1, 3], device="cuda")
torch.cuda.set_sync_debug_mode("error")
for name, fn in (
("cpu", lambda: x.cpu()),
("tolist", lambda: x.tolist()),
("bool(any)", lambda: bool((x < 0).any())),
# The scalar is staged through a pageable host tensor: a hidden sync.
("indexed scalar assignment", lambda: flags.__setitem__(slots, False)),
("pageable upload", lambda: torch.tensor([1, 2, 3], device="cuda")),
):
with pytest.raises(RuntimeError, match="synchronizing"):
fn()
# The forms the data plane is allowed to use.
flags.index_fill_(0, slots, False)
x.to("cpu", non_blocking=True)
torch.tensor([1, 2, 3], pin_memory=True).to("cuda", non_blocking=True)
event = torch.cuda.Event()
event.record()
event.synchronize()
torch.cuda.set_sync_debug_mode(0)
assert flags.tolist() == [True, False, True, False, True, True, True, True]
@requires_cuda
def test_allow_host_sync_scopes_the_exemption(sync_debug_off):
x = torch.arange(4, device="cuda")
torch.cuda.set_sync_debug_mode("error")
with allow_host_sync("test"):
assert x.tolist() == [0, 1, 2, 3]
assert torch.cuda.get_sync_debug_mode() == 2
with pytest.raises(RuntimeError, match="synchronizing"):
x.tolist()
torch.cuda.set_sync_debug_mode(0)
with allow_host_sync("test"):
x.tolist()
assert torch.cuda.get_sync_debug_mode() == 0
@requires_cuda
def test_serving_always_arms_the_check(monkeypatch, sync_debug_off):
# Unset, it warns.
monkeypatch.delenv("TOKENSPEED_DATA_PLANE_SYNC_DEBUG", raising=False)
assert envs.TOKENSPEED_DATA_PLANE_SYNC_DEBUG.get() == "warn"
device_module.arm_data_plane_sync_debug("cuda")
assert torch.cuda.get_sync_debug_mode() == 1
torch.cuda.set_sync_debug_mode(0)
monkeypatch.setenv("TOKENSPEED_DATA_PLANE_SYNC_DEBUG", "error")
device_module.arm_data_plane_sync_debug("cuda")
assert torch.cuda.get_sync_debug_mode() == 2
@pytest.mark.parametrize("mode", ["default", "off", "0", "loud"])
def test_the_check_cannot_be_disabled(monkeypatch, mode):
monkeypatch.setenv("TOKENSPEED_DATA_PLANE_SYNC_DEBUG", mode)
with pytest.raises(ValueError, match="cannot be disabled"):
device_module.arm_data_plane_sync_debug("cuda")
def test_host_to_device_copies_lists_and_strided_tensors():
assert host_to_device(
[[1, 2], [3, 4]], dtype=torch.int32, device="cpu"
).tolist() == [
[1, 2],
[3, 4],
]
table = torch.arange(12).reshape(3, 4)
out = host_to_device(table[:, 1:3], dtype=torch.int64, device="cpu")
assert out.is_contiguous()
assert torch.equal(out, table[:, 1:3])
assert host_to_device([], dtype=torch.int64, device="cpu").shape == (0,)
@requires_cuda
def test_host_to_device_does_not_wait_for_the_stream(sync_debug_off):
# Long enough that copying it from a strided source, even a pinned one,
# makes the driver stage it through pageable memory and wait.
table = torch.arange(3 * (1 << 18)).reshape(3, -1)
chunk = table[:, 2 : 2 + (1 << 17)]
values = list(range(1000))
# The first pinned buffer of a size comes from cudaHostAlloc, which waits.
host_to_device(chunk, dtype=torch.int64, device="cuda")
host_to_device(values, dtype=torch.int32, device="cuda")
torch.cuda.synchronize()
torch.cuda._sleep(1 << 30)
in_flight = torch.cuda.Event()
in_flight.record()
torch.cuda.set_sync_debug_mode("error")
from_tensor = host_to_device(chunk, dtype=torch.int64, device="cuda")
from_list = host_to_device(values, dtype=torch.int32, device="cuda")
torch.cuda.set_sync_debug_mode(0)
assert not in_flight.query()
torch.cuda.synchronize()
assert torch.equal(from_tensor.cpu(), chunk)
assert from_list.tolist() == values
@requires_cuda
def test_host_to_device_refuses_device_tensors():
with pytest.raises(ValueError, match="host values"):
host_to_device(torch.arange(4, device="cuda"), dtype=torch.int64, device="cuda")
@requires_cuda
def test_host_to_device_refuses_graph_capture():
graph = torch.cuda.CUDAGraph()
stream = torch.cuda.Stream()
with torch.cuda.stream(stream):
with pytest.raises(RuntimeError, match="graph capture"):
with torch.cuda.graph(graph, stream=stream):
host_to_device([1, 2], dtype=torch.int32, device="cuda")