Fifth of five; stacked on #38049. The split gave every namespace a file, but only for the half an operator types. This is the other half. ## The parallel quotients are declared, not written out `attn_tp_size` and its five siblings were sixty lines of near-identical properties in the runtime context, a file away from the leaves they are quotients of, so reading `parallel.py` told you what you could set and nothing about what that decides. They are declared in `Parallel` now, in the same class as those leaves. They carry no annotation, so they are not dataclass fields and `collect_input_fields` never puts them on the record -- the same mechanism that already keeps `_NS_PATH` off it. That is the right exclusion: a quotient has no operator input to preserve, and the record is what crosses a process boundary, where a stamped width is one an elastic scale-up will not refresh. ## A quotient is a value in the bag, like every other derived one `_derived_width` answered from a stamp or, failing that, a live process group. The group read could never disagree with the stamp: - `initialize_model_parallel` stamps all six as its last statement, unconditionally; - an elastic scale-up restamps `attn_dp_size` through `update_dp_attention_post_scale` -- the comment claiming it does *not* was wrong; - no hardware backend builds groups of its own; - `multimodal_gen`, which has its own `initialize_model_parallel` and does not stamp, never reads a quotient. So a built group was always already stamped, and the group read goes -- and with it the last reason for a quotient to be resolved on every read. Every input to `derive_parallel_widths` is a record field. `dcp_enabled` is `decode_context_parallel_size > 1`, not a fact about a built group; it was spelled `_DCP is not None`, which is a longer way to say the same thing. So the six are fixed once the configuration is fixed -- the same test every other `Derived(fn=...)` in this PR passes. They are declared the same way and computed the same way: once, at publish, into ordinary bag leaves. What remains is override -> stamp -> published leaf. The stamp stays above the leaf because an elastic scale-up restamps `attn_dp_size`; the override stays on top because that is how a test names a width. ## One answer for the config-derived predicates `enable_mamba_extra_buffer` and its lazy variant, `is_ep_joiner`, `is_ep_scale_joiner`, `is_startup_weight_load_overlap`: each existed as a `ServerArgs` member for the resolution pipeline and, for most of them, again as a `runtime_context` function for readers after publish. Three places to keep saying the same thing. A `Derived(fn=...)` is a pure function of the published configuration, so `publish` computes it once and stores it as an ordinary bag leaf -- a plain attribute load, which is what a read inside compiled model code needs. The function is handed the whole resolved config rather than the bag it lands in, because a derivation is free to span namespaces and the mamba one does: it reads `memory.disable_radix_cache` alongside its own `exec.mamba` strategy, which is why it could never have been a method on either bag. The pre-publish helpers stay -- resolution needs the predicate before there is a bag to read -- and three readers keep them, because they run before their own process publishes: `initialize_dp_attention`, which the weight-cache daemon calls while building its groups thirty lines before its `publish`, and `PortArgs.init_new`, a factory handed the record that already reads eighteen other fields off it. ## Notes for a reviewer **Overriding a leaf does not move its quotient.** `override(tp_size=2)` leaves `attn_tp_size` where the published config put it, because nothing is recomputed on read. A test states a topology by publishing a config -- which is what a real process does -- or by naming the width it wants, `override(attn_tp_size=2)`. Six tests say it that way now. This is the price of having one answer computed once, and it is the same price every other derived value in the config already carries. A caller that reads a quotient without publishing or overriding now gets an explicit error naming the field, instead of a default that an uninitialised group happened to supply. One fixture was in that state -- `TestMlaWriteDoorsUnderDcp` built a bare pool and asked whether DCP was on -- and it publishes a config now, which is what the process it stands in for does. Eighteen sites read these predicates without calling them. That is correct -- they are properties -- but it is worth saying they were checked, because a census that assumes otherwise reports eighteen always-true conditions. ## The skill that documents this subsystem is updated with it `.claude/rules/modify-component-must-read.md` points at `.claude/skills/sglang-runtime-context/SKILL.md` before anyone touches these files, so a stale sentence there is a wrong instruction rather than a stale note. Four of its load-bearing statements stopped being true across this series and are corrected here: `NS(...)` is no longer how a field states its namespace (the declaring class is); the DCP degrade rule is gone, because the quotients are not live reads; `mamba_extra_buffer_enabled()` and the other predicate functions it named as the shape to copy no longer exist; and the namespace-coverage ratchet is described in terms of the marker. The docstring of `test_server_args_namespaces.py` said the same thing and is fixed too. The consequence a test author actually trips over is stated there as well: overriding a leaf no longer moves its quotient, so a topology is stated by publishing a config or by naming the width. ## Verification A full registered-unit sweep (648 files) against this stack's merge-base: 19 failures on both sides, the same 19 -- AMD `gfx950`, `modelopt`, `cuda_vmm`, `weight_checker` and friends, none of them config. The narrower 139-file config sweep used earlier in this series does not contain the files this change reaches -- `test_kv_index_translator` never names `get_parallel()`, it constructs an object that does -- which is why the baseline differential over everything is what is quoted here.
236 lines
9.3 KiB
Python
236 lines
9.3 KiB
Python
"""Coverage lint for the ServerArgs -> RuntimeContext namespace split.
|
|
|
|
Every ServerArgs field must resolve to a namespace, and every path must be one of
|
|
the known domains. A field gets its namespace from the ``arg_groups/fields/``
|
|
class that declares it -- each carries the ``_NS_PATH`` it stands for, so the
|
|
module a declaration lives in *is* the answer, and there is no per-field marker
|
|
to forget. (``NS("<path>")`` survives for the one shape a class cannot express:
|
|
an ad-hoc dataclass spanning namespaces, which the config-bag tests build.)
|
|
|
|
This is the guardrail that fails when an upstream PR adds a field to a namespace
|
|
class that has no ``_NS_PATH``, or adds one outside the taxonomy below.
|
|
"""
|
|
|
|
import dataclasses
|
|
import unittest
|
|
|
|
from sglang.srt.arg_groups.arg_utils import namespace_of
|
|
from sglang.srt.server_args import ServerArgs
|
|
from sglang.test.ci.ci_register import register_cpu_ci
|
|
from sglang.test.test_utils import CustomTestCase
|
|
|
|
register_cpu_ci(est_time=31, suite="base-a-test-cpu")
|
|
|
|
# Locked taxonomy (global_context/11-server-args-namespace-split.md).
|
|
VALID_NAMESPACES = {
|
|
"parallel",
|
|
"device",
|
|
"model",
|
|
"schedule",
|
|
"memory",
|
|
"spec",
|
|
"lora",
|
|
"mm",
|
|
"disagg",
|
|
"serving",
|
|
"observability",
|
|
"exec.kernel",
|
|
"exec.moe",
|
|
"exec.graph",
|
|
"exec.comm",
|
|
"exec.mamba",
|
|
"exec.overlap",
|
|
"exec.offload",
|
|
"exec.dllm",
|
|
"exec.deterministic",
|
|
"exec.features",
|
|
}
|
|
|
|
|
|
def _field_names():
|
|
return {f.name for f in dataclasses.fields(ServerArgs)}
|
|
|
|
|
|
class TestServerArgsNamespaces(CustomTestCase):
|
|
def test_no_module_shadows_a_bag_accessor(self):
|
|
"""An accessor name bound twice in one module is a silent wrong read.
|
|
|
|
This has happened twice. Once a module imported `get_model` from the
|
|
context and a same-named helper from elsewhere, and once `get_device`
|
|
-- which names three different things in this tree: the bag accessor,
|
|
the device-string utility, and a platform method. The second import
|
|
wins, the converted line calls the wrong callable, and the failure is
|
|
an AttributeError on whichever branch reaches it, which for a
|
|
per-pass recorder or a specific accelerator can be none of the ones a
|
|
CPU suite runs. Nothing else notices; a name scan looks fine.
|
|
"""
|
|
import ast
|
|
import collections
|
|
import pathlib as _pathlib
|
|
|
|
import sglang
|
|
|
|
srt = _pathlib.Path(sglang.__file__).resolve().parent / "srt"
|
|
context_module = ast.parse(
|
|
(srt / "runtime_context.py").read_text(encoding="utf-8-sig")
|
|
)
|
|
accessors = {
|
|
node.name
|
|
for node in context_module.body
|
|
if isinstance(node, ast.FunctionDef) and node.name.startswith("get_")
|
|
}
|
|
self.assertGreater(len(accessors), 15, "the accessor derivation broke")
|
|
|
|
shadowed = []
|
|
for path in sorted(srt.rglob("*.py")):
|
|
if path.name == "runtime_context.py":
|
|
continue
|
|
source = path.read_text(encoding="utf-8-sig")
|
|
if "runtime_context" not in source:
|
|
continue
|
|
try:
|
|
tree = ast.parse(source)
|
|
except SyntaxError:
|
|
self.fail(f"unparsable module in the census: {path}")
|
|
bindings = collections.defaultdict(set)
|
|
for node in ast.walk(tree):
|
|
if isinstance(node, ast.ImportFrom):
|
|
origin = node.module or ""
|
|
kind = (
|
|
"context"
|
|
if origin.endswith("runtime_context")
|
|
else f"{origin or '.'}"
|
|
)
|
|
for alias in node.names:
|
|
bindings[alias.asname or alias.name].add((kind, node.lineno))
|
|
elif isinstance(node, ast.Import):
|
|
for alias in node.names:
|
|
bindings[(alias.asname or alias.name).split(".")[0]].add(
|
|
("import", node.lineno)
|
|
)
|
|
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
bindings[node.name].add(("def", node.lineno))
|
|
elif isinstance(node, ast.Assign):
|
|
for target in node.targets:
|
|
if isinstance(target, ast.Name):
|
|
bindings[target.id].add(("assign", node.lineno))
|
|
for name, where in bindings.items():
|
|
if name not in accessors:
|
|
continue
|
|
kinds = {kind for kind, _ in where}
|
|
# The same accessor imported from the context more than once
|
|
# (module level plus a lazy import inside a function) is one
|
|
# object under one name; a *different* origin is the hazard.
|
|
if "context" in kinds and kinds - {"context"}:
|
|
shadowed.append(
|
|
f"{path.relative_to(srt)}: {name} <- "
|
|
+ ", ".join(
|
|
f"{k}@{l}" for k, l in sorted(where, key=lambda w: w[1])
|
|
)
|
|
)
|
|
self.assertEqual(
|
|
shadowed,
|
|
[],
|
|
"a bag accessor shares its name with another binding in the same "
|
|
"module, so the converted reads call whichever import came last; "
|
|
"alias one of them:\n " + "\n ".join(shadowed),
|
|
)
|
|
|
|
def test_the_readers_agree_with_the_namespace_metadata(self):
|
|
"""Two independent sources say where a leaf lives; they must match.
|
|
|
|
The metadata is one source and the ~2000 hand-written reads
|
|
(`get_schedule().chunked_prefill_size`) are the other. Checking the
|
|
projection against the metadata cannot catch a field assigned to the
|
|
wrong group -- both sides come from the same marker, so the check is
|
|
true by construction. The readers are written by hand, so a
|
|
disagreement means one of the two is wrong, and every reader on the
|
|
losing side raises `has no leaf/subgroup` at runtime on whichever
|
|
branch reaches it first.
|
|
"""
|
|
import ast
|
|
import pathlib as _pathlib
|
|
|
|
import sglang
|
|
|
|
srt = _pathlib.Path(sglang.__file__).resolve().parent / "srt"
|
|
mapping = namespace_of(ServerArgs)
|
|
accessors = {
|
|
f"get_{group}" for group in {p.split(".")[0] for p in mapping.values()}
|
|
}
|
|
|
|
sites = 0
|
|
disagreements = []
|
|
for path in sorted(srt.rglob("*.py")):
|
|
source = path.read_text(encoding="utf-8-sig")
|
|
if not any(name in source for name in accessors):
|
|
continue
|
|
try:
|
|
tree = ast.parse(source)
|
|
except SyntaxError:
|
|
self.fail(f"unparsable module in the census: {path}")
|
|
for node in ast.walk(tree):
|
|
if not isinstance(node, ast.Attribute):
|
|
continue
|
|
chain, cursor = [], node
|
|
while isinstance(cursor, ast.Attribute):
|
|
chain.append(cursor.attr)
|
|
cursor = cursor.value
|
|
if not (
|
|
isinstance(cursor, ast.Call)
|
|
and isinstance(cursor.func, ast.Name)
|
|
and cursor.func.id in accessors
|
|
):
|
|
continue
|
|
chain.reverse()
|
|
field = chain[-1]
|
|
if field not in mapping:
|
|
continue
|
|
sites += 1
|
|
read = [cursor.func.id[len("get_") :]] + chain[:-1]
|
|
if read[:2] == ["parallel", "config"]:
|
|
# `config` on `get_parallel()` is the tier hop, not a
|
|
# sub-namespace: bare names there are the live topology.
|
|
del read[1]
|
|
if mapping[field].split(".") != read:
|
|
disagreements.append(
|
|
f"{path.relative_to(srt)}:{node.lineno} reads "
|
|
f"{'.'.join(read)}.{field}, metadata says "
|
|
f"{mapping[field]}.{field}"
|
|
)
|
|
self.assertEqual(
|
|
disagreements,
|
|
[],
|
|
"a reader and the namespace metadata disagree about where a leaf "
|
|
"lives; one of them is wrong:\n " + "\n ".join(disagreements),
|
|
)
|
|
self.assertGreater(
|
|
sites,
|
|
1500,
|
|
f"only {sites} bag reads were matched; the scan broke and this "
|
|
"check stopped covering anything",
|
|
)
|
|
|
|
def test_every_field_has_a_namespace(self):
|
|
nsmap = namespace_of(ServerArgs)
|
|
missing = sorted(_field_names() - set(nsmap))
|
|
self.assertFalse(
|
|
missing,
|
|
"ServerArgs fields missing an NS(...) marker "
|
|
f"(assign a namespace in server_args.py): {missing}",
|
|
)
|
|
|
|
def test_all_namespaces_are_known(self):
|
|
nsmap = namespace_of(ServerArgs)
|
|
bad = {f: p for f, p in nsmap.items() if p not in VALID_NAMESPACES}
|
|
self.assertFalse(bad, f"unknown namespace paths (typo or new domain?): {bad}")
|
|
|
|
def test_namespace_map_covers_all_fields(self):
|
|
nsmap = namespace_of(ServerArgs)
|
|
self.assertEqual(set(nsmap), _field_names())
|
|
self.assertGreaterEqual(len(nsmap), 440)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|