Files
tokenspeed/test/runtime/test_encoder_batching.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

245 lines
8.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.
"""Budget boundaries and shared encoder dispatch regression tests."""
import os
import sys
from dataclasses import dataclass
from types import SimpleNamespace
from unittest.mock import patch
import pytest
import torch
# CI registration (AST-parsed, runtime no-op).
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=30, suite="runtime-1gpu")
from tokenspeed.runtime.distributed.mapping import Mapping # noqa: E402
from tokenspeed.runtime.multimodal.encoder_batching import ( # noqa: E402
pack_encoder_batches,
)
from tokenspeed.runtime.multimodal.encoder_cudagraph import ( # noqa: E402
EncoderForwardStepRunner,
VisionEncoderCudaGraphAdapter,
pad_cu_seqlens,
)
@pytest.mark.parametrize(
"tokens,sequences,limit,items,metadata,expected",
[
([6, 2, 4], [1, 1, 1], 6, None, None, [[1, 2], [0]]),
([2] * 9, [1] * 9, 20, None, None, [list(range(9))]),
([2] * 3, [1] * 3, 20, 2, None, [[0, 1], [2]]),
([2, 2, 2], [2, 2, 1], 20, None, 3, [[0], [1, 2]]),
([21, 2, 3], [1, 1, 1], 20, None, None, [[1, 2], [0]]),
([1, 2], [5, 1], 20, None, 3, [[0], [1]]),
([], [], 20, None, None, []),
],
)
def test_pack(tokens, sequences, limit, items, metadata, expected):
assert (
pack_encoder_batches(
tokens,
sequences,
max_tokens=limit,
max_items=items,
max_metadata_sequences=metadata,
)
== expected
)
@pytest.mark.parametrize(
"tokens,sequences,limit,items,metadata",
[
([1], [], 10, None, None),
([-1], [1], 10, None, None),
([1], [-1], 10, None, None),
([1], [1], 0, None, None),
([1], [1], 10, 0, None),
([1], [1], 10, None, 0),
],
)
def test_invalid_budget(tokens, sequences, limit, items, metadata):
with pytest.raises(ValueError):
pack_encoder_batches(
tokens,
sequences,
max_tokens=limit,
max_items=items,
max_metadata_sequences=metadata,
)
@dataclass
class Batch:
encoder_output_tokens: list[int]
metadata_sequences: list[int]
indices: list[int]
def num_items(self):
return len(self.indices)
def select(self, indices):
return Batch(
[self.encoder_output_tokens[i] for i in indices],
[self.metadata_sequences[i] for i in indices],
[self.indices[i] for i in indices],
)
def test_runner_restores_order_and_preserves_eager_fallback():
adapter = SimpleNamespace(
device=torch.device("cpu"),
dtype=torch.float32,
modality_name="image",
capture_tp_size=1,
capture_tp_group=None,
)
runner = EncoderForwardStepRunner(
adapter=adapter,
budget_range=(2, 8),
max_batch_size=4,
max_metadata_sequences_per_batch=4,
metadata_sequence_budget_from_encoder_output_budget=False,
)
batch = Batch([9, 2, 4, 2], [1] * 4, [0, 1, 2, 3])
def execute(part):
return torch.cat(
[
torch.full((n, 1), i, dtype=torch.float32)
for n, i in zip(part.encoder_output_tokens, part.indices, strict=True)
]
)
with patch.object(runner, "_run_eager", side_effect=execute) as eager, patch.object(
runner, "_run_budget_graph", side_effect=lambda part, budget: execute(part)
) as graph:
output = runner._dispatch(batch)
assert graph.call_count == eager.call_count == 1
assert graph.call_args.args[1] == 8
assert eager.call_args.args[0].indices == [0]
for i, (rows, tensor) in enumerate(
zip(batch.encoder_output_tokens, output, strict=True)
):
torch.testing.assert_close(
tensor, torch.full((rows, 1), i, dtype=torch.float32)
)
@pytest.mark.skipif(
not (torch.cuda.is_available() and torch.version.cuda is not None),
reason="Qwen3 vision graphs require an NVIDIA GPU",
)
def test_budget_graph_ignores_what_an_earlier_replay_left_in_its_padding():
from transformers.models.qwen3_vl.configuration_qwen3_vl import (
Qwen3VLVisionConfig,
)
from tokenspeed.runtime.models.qwen3_vision import Qwen3VLMoeVisionModel
config = Qwen3VLVisionConfig(
depth=2,
hidden_size=128,
intermediate_size=256,
num_heads=2,
patch_size=2,
temporal_patch_size=2,
spatial_merge_size=2,
out_hidden_size=128,
num_position_embeddings=64,
deepstack_visual_indexes=[0],
)
torch.manual_seed(0)
tower = Qwen3VLMoeVisionModel(
config, Mapping(rank=0, world_size=1), prefix="visual"
)
tower = tower.cuda().bfloat16().eval()
with torch.no_grad():
for name, param in tower.named_parameters():
if "norm" in name:
param.fill_(1.0 if name.endswith("weight") else 0.0)
else:
param.normal_(0, 0.05)
def pre_encode(items):
grid = torch.tensor([[1, h, w] for h, w in items], device="cuda")
generator = torch.Generator(device="cuda").manual_seed(len(items))
patches = torch.randn(
int(grid.prod(-1).sum()),
24,
device="cuda",
dtype=torch.bfloat16,
generator=generator,
)
if items == [(32, 32)]:
patches.fill_(float("nan"))
return tower.prepare_patch_embed(patches, grid), grid
runner = EncoderForwardStepRunner(
adapter=VisionEncoderCudaGraphAdapter(
tower=tower,
pre_encode=pre_encode,
post_encode=lambda outs, grid: torch.cat(outs),
out_div=4,
merge=2,
input_feature_shape=(1, 128),
modality_name="vision",
capture_tp_size=1,
capture_tp_group=None,
),
budget_range=(16, 256),
metadata_sequence_budget_from_encoder_output_budget=True,
)
# A NaN batch fills the 256-token graph, then a 150-token batch leaves 424 of its rows as padding.
items = [(24, 24), (6, 4)]
with torch.no_grad():
runner([(32, 32)])
output = runner(items)
tokens, grid = pre_encode(items)
expected = tower.forward_blocks(tokens, tower.prepare_metadata(grid))
assert sorted(runner.budget_graphs) == [16, 32, 64, 128, 256]
torch.testing.assert_close(output, expected, atol=1e-2, rtol=1e-2)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_cu_seqlens_padding_does_not_synchronize():
# A budget graph's replay pads its cu_seqlens on the forward thread,
# behind the step in flight.
cu_seqlens = torch.tensor([0, 10, 25], dtype=torch.int32).to("cuda")
torch.cuda.synchronize()
previous_mode = torch.cuda.get_sync_debug_mode()
try:
torch.cuda.set_sync_debug_mode("error")
padded = pad_cu_seqlens(cu_seqlens, 25, 64, 4, "vision")
finally:
torch.cuda.set_sync_debug_mode(previous_mode)
# Padding rows 25..64 run as sequences of at most PADDING_SEQUENCE_ROWS;
# the tail repeats the last offset up to the graph's fixed shape.
assert padded.tolist()[:3] == [0, 10, 25]
assert padded.tolist()[-1] == 64
assert padded.tolist() == sorted(padded.tolist())