mirror of
https://github.com/lightseekorg/tokenspeed.git
synced 2026-12-04 10:26:50 +08:00
The RFC is `docs/rfcs/0003-forward-reload.md` and the guide `docs/guides/forward-reload.md`. Kernel and model work iterates as benchmark or profile, edit, measure again, and on large models the restart dominates that loop: Beam-1.0 NVFP4 at TP4 restarts in 286 s with warm caches. This adds a development-only control operation, `reload_forward` (`ts reload-forward`), that brings edited model, layer and kernel code into a running engine: it drains, flushes the prefix caches, re-executes the edited Python modules on every rank in lockstep, warms their kernels and recaptures the CUDA graphs, then resumes. Weights, the KV cache, communicators and tuned tactics stay, and one profiler session spans every iteration. The same Beam reload takes 72 s. - Off unless the server starts with `--allow-reload-forward`; without it the control loop refuses the call on arrival, before draining anything. - `tokenspeed_kernel.hot_reload` re-executes edited modules and their dependents in place and patches functions, classes, closures, kernel registrations and the containers that hold them; module data returns to its import-time value and the reply names what was reset. - A failed edit (syntax error, a raising warmup or capture) is undone, and the previous code keeps serving. - Warmup and every capture start from startup's dummy inputs: serving leaves an M-RoPE position override, the slots' cached lengths, the last step's draft trees and the mid-prefill flag in them. - The engine gates the reload like a weight operation across attention-DP ranks, with a timeout and `wait` and `abort` modes; it is refused while memory is released, during a keep pause, or while another pause, release or reload runs. Needs a restart: CUDA C++ kernels, `__init__` and layout changes, attention or MoE backend changes and vision encoder graphs. Pipeline parallelism and EPD are untested. ## Validation GB200 (details and tables in the RFC): - Beam-1.0 NVFP4 TP4: a slowed Triton kernel reached all four ranks inside the captured graphs (c=64 TPOT 11.20 to 34.11 ms), and restoring it returned 11.25 ms; GPU memory was flat across reloads and no request failed. 16 reloads while tuning Beam's decode took c=64 TPOT from 11.61 to 10.22 ms without a restart. - Qwen3-8B TP1 and attention DP2: an edit changes greedy output, the revert restores it exactly, and failed edits are undone with the server serving. - Speculative decoding with EAGLE3 chain and tree, MTP, DFlash and DSpark at TP1, TP2, attention DP2 and TP4: negating the draft's logits drops acceptance to 1.00, and restoring the draft restores acceptance and the exact greedy outputs. - `tokenspeed-kernel/test/test_hot_reload.py`, `test_compile_monitor.py`, the Rust state-machine tests in `ts-control` and `test/runtime/test_forward_reload_gpu.py` pass on this branch. --------- Signed-off-by: Nicolas <nperrin.ai@gmail.com> Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
244 lines
8.7 KiB
Python
244 lines
8.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.
|
|
|
|
"""The boot path's capture step: where it is called and what it covers.
|
|
|
|
The checks read source text instead of importing the runtime: what moved is
|
|
boot sequencing, and a sequencing test should not need the model to load.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import ast
|
|
import os
|
|
import pathlib
|
|
import sys
|
|
|
|
import pytest
|
|
|
|
# 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__))))
|
|
from ci_system.ci_register import register_cuda_ci # noqa: E402
|
|
|
|
register_cuda_ci(est_time=5, suite="runtime-1gpu")
|
|
|
|
_RUNTIME = (
|
|
pathlib.Path(__file__).resolve().parents[2]
|
|
/ "python"
|
|
/ "tokenspeed"
|
|
/ "runtime"
|
|
/ "execution"
|
|
)
|
|
_STEP_OPERATIONS = frozenset({"autotune", "freeze", "capture", "capture_graphs"})
|
|
|
|
|
|
def _tree(name: str) -> ast.Module:
|
|
return ast.parse((_RUNTIME / name).read_text())
|
|
|
|
|
|
def _function(tree: ast.AST, name: str) -> ast.FunctionDef:
|
|
return next(
|
|
node
|
|
for node in ast.walk(tree)
|
|
if isinstance(node, ast.FunctionDef) and node.name == name
|
|
)
|
|
|
|
|
|
def _attribute_calls(node: ast.AST) -> list[ast.Call]:
|
|
return [
|
|
call
|
|
for call in ast.walk(node)
|
|
if isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute)
|
|
]
|
|
|
|
|
|
def _serving_captures(builder: ast.AST) -> list[int]:
|
|
"""Lines where the boot path runs the serving capture on its executor."""
|
|
return [
|
|
call.lineno
|
|
for call in ast.walk(builder)
|
|
if isinstance(call, ast.Call)
|
|
and isinstance(call.func, ast.Name)
|
|
and call.func.id == "_capture_serving_graphs"
|
|
and call.args
|
|
and isinstance(call.args[0], ast.Name)
|
|
and call.args[0].id == "executor"
|
|
]
|
|
|
|
|
|
def test_the_boot_path_runs_the_capture_step():
|
|
"""The one line that keeps boot behaviour unchanged has to be asserted.
|
|
|
|
Construction no longer tunes, freezes or captures, so ``build_device_side``
|
|
calling ``capture_graphs`` (through ``_capture_serving_graphs``, which a
|
|
forward reload repeats) is the whole of the change's boot contract. With
|
|
that call gone the engine boots untuned, with an unfrozen workspace, no
|
|
graphs and no post-startup seed -- and the first decode dies inside
|
|
``ForwardStepRunner`` on a graph key that was never captured, because
|
|
``_can_use_graph`` answers from ``bs <= max_capture_bs``, not from
|
|
membership in ``self.graphs``.
|
|
"""
|
|
builder = _function(_tree("device.py"), "build_device_side")
|
|
boot = _serving_captures(builder)
|
|
assert len(boot) == 1, boot
|
|
serving = _function(_tree("device.py"), "_capture_serving_graphs")
|
|
calls = [
|
|
call
|
|
for call in _attribute_calls(serving)
|
|
if call.func.attr == "capture_graphs"
|
|
and isinstance(call.func.value, ast.Name)
|
|
and call.func.value.id == "executor"
|
|
]
|
|
assert len(calls) == 1, calls
|
|
|
|
|
|
def test_the_capture_step_precedes_the_per_rank_memory_summary():
|
|
"""The summary reads ``memory_allocated`` at the instant it runs.
|
|
|
|
Graph memory only appears in the ``activations + graphs`` row if the
|
|
graphs are already captured, so the step has to sit above the summary.
|
|
"""
|
|
builder = _function(_tree("device.py"), "build_device_side")
|
|
capture = _serving_captures(builder)
|
|
summary = [
|
|
call.lineno
|
|
for call in ast.walk(builder)
|
|
if isinstance(call, ast.Call)
|
|
and isinstance(call.func, ast.Name)
|
|
and call.func.id == "log_gpu_memory_summary"
|
|
]
|
|
assert capture and summary
|
|
assert max(capture) < min(summary), (capture, summary)
|
|
|
|
|
|
def test_nothing_the_constructor_reaches_tunes_freezes_or_captures():
|
|
"""Transitive, so the seam cannot be closed behind one helper.
|
|
|
|
Checking ``__init__``'s own call names only rules out the literal move
|
|
back; a ``self._install_graphs()`` added to the constructor reads as an
|
|
unrelated attribute call and would pass. Follow every ``self.<method>``
|
|
the constructor can reach instead.
|
|
"""
|
|
tree = _tree("model_executor.py")
|
|
executor = next(
|
|
node
|
|
for node in tree.body
|
|
if isinstance(node, ast.ClassDef) and node.name == "ModelExecutor"
|
|
)
|
|
methods = {
|
|
node.name: node for node in executor.body if isinstance(node, ast.FunctionDef)
|
|
}
|
|
|
|
reached: set[str] = set()
|
|
offenders: list[str] = []
|
|
frontier = ["__init__"]
|
|
while frontier:
|
|
name = frontier.pop()
|
|
if name in reached:
|
|
continue
|
|
reached.add(name)
|
|
for call in _attribute_calls(methods[name]):
|
|
attr = call.func.attr
|
|
if attr in _STEP_OPERATIONS:
|
|
offenders.append(f"{name} -> {attr} (line {call.lineno})")
|
|
if (
|
|
isinstance(call.func.value, ast.Name)
|
|
and call.func.value.id == "self"
|
|
and attr in methods
|
|
):
|
|
frontier.append(attr)
|
|
|
|
assert "__init__" in reached
|
|
assert not offenders, offenders
|
|
|
|
|
|
def test_the_step_names_every_operation_the_constructor_gave_up():
|
|
"""The move must be complete, not partial: tuning left, the rest stayed.
|
|
|
|
Tuning left ``capture_graphs`` when the probe made it run twice -- a
|
|
captured graph keeps the tactic it was captured with, and the tuner's
|
|
token bound is a once-per-process call -- so the boot path now names it
|
|
directly, alongside the step that freezes and captures.
|
|
"""
|
|
step = _function(_tree("model_executor.py"), "capture_graphs")
|
|
names = {call.func.attr for call in _attribute_calls(step)}
|
|
builder = _function(_tree("device.py"), "build_device_side")
|
|
boot_names = {call.func.attr for call in _attribute_calls(builder)}
|
|
|
|
# Only tuning moved; freeze and capture stay where the constructor left them.
|
|
assert {"freeze", "capture"} <= names, names
|
|
assert "autotune" in boot_names, boot_names
|
|
assert "autotune" not in names, names
|
|
|
|
|
|
def test_the_step_runs_its_operations_in_the_order_the_constructor_did():
|
|
"""Freeze, capture decode, capture prefill; the boot tunes before and seeds after.
|
|
|
|
Tuning and capture draw from the generator, so the serving capture seeds
|
|
once they are done, exactly where the constructor used to.
|
|
"""
|
|
step = _function(_tree("model_executor.py"), "capture_graphs")
|
|
sequence = [
|
|
call.func.attr
|
|
for call in _attribute_calls(step)
|
|
if call.func.attr in _STEP_OPERATIONS
|
|
]
|
|
assert sequence == ["freeze", "capture", "capture"]
|
|
|
|
builder = _function(_tree("device.py"), "build_device_side")
|
|
tune = [
|
|
call.lineno
|
|
for call in _attribute_calls(builder)
|
|
if call.func.attr == "autotune"
|
|
]
|
|
capture = _serving_captures(builder)
|
|
assert len(tune) == 1, tune
|
|
assert max(tune) < min(capture), (tune, capture)
|
|
|
|
# Mutation-checked: a probe on untuned graphs prices kernels that never serve.
|
|
rebind = [
|
|
call.lineno
|
|
for call in ast.walk(builder)
|
|
if isinstance(call, ast.Call)
|
|
and isinstance(call.func, ast.Name)
|
|
and call.func.id == "_rebind_under_reserve"
|
|
]
|
|
assert len(rebind) == 1, rebind
|
|
assert max(tune) < min(rebind), (tune, rebind)
|
|
|
|
serving = _function(_tree("device.py"), "_capture_serving_graphs")
|
|
captured = [
|
|
call.lineno
|
|
for call in _attribute_calls(serving)
|
|
if call.func.attr == "capture_graphs"
|
|
]
|
|
seed = [
|
|
call.lineno
|
|
for call in ast.walk(serving)
|
|
if isinstance(call, ast.Call)
|
|
and isinstance(call.func, ast.Name)
|
|
and call.func.id == "set_random_seed"
|
|
]
|
|
assert seed and captured and max(captured) < min(seed), (captured, seed)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(pytest.main([__file__, "-v"]))
|