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.
191 lines
7.4 KiB
Python
191 lines
7.4 KiB
Python
"""Tests for ServerArgs CLI argument auto-derivation from A[T, Arg(...)] annotations.
|
|
|
|
Each test covers a distinct edge case in how add_cli_args_from_dataclass
|
|
translates field annotations into argparse arguments.
|
|
"""
|
|
|
|
import argparse
|
|
import unittest
|
|
|
|
from sglang.srt.arg_groups.overrides import resolution_result
|
|
from sglang.srt.runtime_context import get_model, publish, reset_context
|
|
from sglang.srt.server_args import ServerArgs
|
|
from sglang.srt.utils.common import configure_media_url_security
|
|
from sglang.test.ci.ci_register import register_cpu_ci
|
|
from sglang.test.test_utils import CustomTestCase
|
|
|
|
register_cpu_ci(est_time=10, suite="base-a-test-cpu")
|
|
|
|
|
|
class TestServerArgsAnnotatedCli(CustomTestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.parser = argparse.ArgumentParser()
|
|
ServerArgs.add_cli_args(cls.parser)
|
|
|
|
def _parse(self, args_list):
|
|
args = self.parser.parse_args(["--model", "dummy"] + args_list)
|
|
server_args = ServerArgs.from_cli_args(args)
|
|
# Parsing hands back the raw record; the cases below read values that
|
|
# resolution normalises, so resolve here the way a launcher would.
|
|
server_args.resolve_once()
|
|
return server_args
|
|
|
|
def test_aliases_and_dest(self):
|
|
"""Field name drives dest; long forms and short aliases both work."""
|
|
cases = [
|
|
("--tp-size", "--tensor-parallel-size", "tp_size"),
|
|
("--pp-size", "--pipeline-parallel-size", "pp_size"),
|
|
("--dp-size", "--data-parallel-size", "dp_size"),
|
|
("--ep-size", "--expert-parallel-size", "ep_size"),
|
|
("--attn-cp-size", "--attention-context-parallel-size", "attn_cp_size"),
|
|
("--moe-dp-size", "--moe-data-parallel-size", "moe_dp_size"),
|
|
]
|
|
for short, long, field in cases:
|
|
with self.subTest(field=field):
|
|
sa_short = self._parse([short, "4"])
|
|
sa_long = self._parse([long, "4"])
|
|
self.assertEqual(getattr(sa_short, field), 4)
|
|
self.assertEqual(getattr(sa_long, field), 4)
|
|
|
|
def test_cli_name_differs_from_field_name(self):
|
|
"""cli_name maps a different CLI flag to the dataclass field via dest."""
|
|
sa = self._parse(
|
|
["--fp8-gemm-backend", "triton", "--fp4-gemm-backend", "marlin"]
|
|
)
|
|
self.assertEqual(sa.fp8_gemm_runner_backend, "triton")
|
|
self.assertEqual(sa.fp4_gemm_runner_backend, "marlin")
|
|
|
|
def test_nargs_question_with_const(self):
|
|
"""nargs='?' + const='' for --model-checksum."""
|
|
self.assertIsNone(self._parse([]).model_checksum)
|
|
self.assertEqual(self._parse(["--model-checksum"]).model_checksum, "")
|
|
self.assertEqual(self._parse(["--model-checksum", "abc"]).model_checksum, "abc")
|
|
|
|
def test_boolean_optional_action(self):
|
|
"""BooleanOptionalAction supports --flag and --no-flag."""
|
|
self.assertIsNone(self._parse([]).experts_shared_outer_loras)
|
|
self.assertTrue(
|
|
self._parse(["--experts-shared-outer-loras"]).experts_shared_outer_loras
|
|
)
|
|
self.assertFalse(
|
|
self._parse(["--no-experts-shared-outer-loras"]).experts_shared_outer_loras
|
|
)
|
|
|
|
def test_json_type_parsers(self):
|
|
"""json.loads and json_list_type parse single-string arguments."""
|
|
sa = self._parse(
|
|
[
|
|
"--extra-metric-labels",
|
|
'{"k": "v"}',
|
|
"--forward-hooks",
|
|
'[{"type": "test"}]',
|
|
]
|
|
)
|
|
self.assertEqual(sa.extra_metric_labels, {"k": "v"})
|
|
self.assertEqual(sa.forward_hooks, [{"type": "test"}])
|
|
|
|
def test_media_url_security_args(self):
|
|
try:
|
|
sa = self._parse(
|
|
[
|
|
"--allowed-media-domains",
|
|
"Media.Example.com.",
|
|
"127.0.0.1",
|
|
"--media-url-max-file-size-mb",
|
|
"32",
|
|
]
|
|
)
|
|
# The normalization is a declaration.
|
|
self.assertEqual(
|
|
resolution_result(sa, "allowed_media_domains"),
|
|
["127.0.0.1", "media.example.com"],
|
|
)
|
|
self.assertEqual(sa.media_url_max_file_size_mb, 32)
|
|
finally:
|
|
configure_media_url_security([], max_file_size_mb=64)
|
|
|
|
def test_media_url_security_args_reject_invalid_values(self):
|
|
try:
|
|
with self.assertRaises(ValueError):
|
|
self._parse(["--allowed-media-domains", "https://media.example.com"])
|
|
with self.assertRaises(ValueError):
|
|
self._parse(["--media-url-max-file-size-mb", "-1"])
|
|
finally:
|
|
configure_media_url_security([], max_file_size_mb=64)
|
|
|
|
def test_literal_auto_derives_choices(self):
|
|
"""Literal type annotations produce argparse choices automatically."""
|
|
sa = self._parse(
|
|
["--deepep-mode", "low_latency", "--elastic-ep-backend", "none"]
|
|
)
|
|
self.assertEqual(sa.deepep_mode, "low_latency")
|
|
self.assertEqual(sa.elastic_ep_backend, "none")
|
|
|
|
def test_image_processor_backend_choices(self):
|
|
for backend in ("auto", "torchvision", "pil"):
|
|
with self.subTest(backend=backend):
|
|
sa = self._parse(["--image-processor-backend", backend])
|
|
self.assertEqual(sa.image_processor_backend, backend)
|
|
|
|
def test_startup_weight_load_mode(self):
|
|
"""The startup loading mode keeps serial as the safe default."""
|
|
serial = self._parse([])
|
|
overlap = self._parse(["--startup-weight-load-mode", "overlap"])
|
|
self.assertEqual(serial.startup_weight_load_mode, "serial")
|
|
self.assertEqual(overlap.startup_weight_load_mode, "overlap")
|
|
# The predicate over that leaf is a bag leaf now, computed at publish.
|
|
for record, expected in ((serial, False), (overlap, True)):
|
|
reset_context()
|
|
self.addCleanup(reset_context)
|
|
publish(record, role="test")
|
|
self.assertIs(get_model().is_startup_weight_load_overlap, expected)
|
|
|
|
with self.assertRaises(SystemExit):
|
|
self.parser.parse_args(
|
|
[
|
|
"--model",
|
|
"dummy",
|
|
"--startup-weight-load-mode",
|
|
"unsupported",
|
|
]
|
|
)
|
|
|
|
def test_deprecated_flags_still_work(self):
|
|
"""Deprecated flags set the correct dest field."""
|
|
sa = self._parse(["--stream-output"])
|
|
self.assertTrue(sa.incremental_streaming_output)
|
|
|
|
def test_combined_parse(self):
|
|
"""Multiple option types parsed together in one invocation."""
|
|
sa = self._parse(
|
|
[
|
|
"--dtype",
|
|
"bfloat16",
|
|
"--tp-size",
|
|
"4",
|
|
"--data-parallel-size",
|
|
"2",
|
|
"--enable-lora",
|
|
"--watchdog-timeout",
|
|
"600",
|
|
"--bucket-time-to-first-token",
|
|
"0.5",
|
|
"1.0",
|
|
"--lora-paths",
|
|
"p1",
|
|
"p2",
|
|
]
|
|
)
|
|
self.assertEqual(sa.dtype, "bfloat16")
|
|
self.assertEqual(sa.tp_size, 4)
|
|
self.assertEqual(sa.dp_size, 2)
|
|
self.assertTrue(sa.enable_lora)
|
|
self.assertEqual(sa.watchdog_timeout, 600.0)
|
|
self.assertEqual(sa.bucket_time_to_first_token, [0.5, 1.0])
|
|
self.assertIsNotNone(sa.lora_paths)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|