From b7eef5f673e78ca1bbf5b039579b7a5eba63fba0 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 23:21:42 +0800 Subject: [PATCH 1/3] Take long options by their full name only (no argparse abbreviations) argparse's default allow_abbrev=True resolved any unique prefix of a long option to that option, so a misspelled name silently set another one: `yeto launch --rollout-num-gpus 8` set --rollout-num-gpus-per-engine. yeto.exact_argparse.ExactArgumentParser turns abbreviations off and, on an unrecognized option, names the options probably meant (same destination, the options it is a prefix of, then difflib's closest spellings). It is used by the `yeto` command tree (sub-parsers inherit the class), the NC pool tool and the Miles island entry. Short options still combine. One repo test relied on the abbreviation: the memory-estimate case full_parameter_fixed_partition passed --rollout-num-gpus 4, which landed on --rollout-num-gpus-per-engine and recorded a colocated layout. It now passes --rl-rollout-gpus 4 and its record is the fixed partition it names. Co-Authored-By: Claude Opus 5.5 --- tests/data/memory_estimate_records.json | 18 ++-- tests/test_exact_option_names.py | 129 ++++++++++++++++++++++++ tests/test_memory_estimate_sampler.py | 2 +- yeto/cli.py | 7 +- yeto/exact_argparse.py | 93 +++++++++++++++++ yeto/launch/nc/cli.py | 3 +- yeto/launch/rl_args.py | 3 +- yeto/rl/adapters/miles/island_entry.py | 5 +- yeto/rl/engine/run_flags.py | 3 +- 9 files changed, 245 insertions(+), 18 deletions(-) create mode 100644 tests/test_exact_option_names.py create mode 100644 yeto/exact_argparse.py diff --git a/tests/data/memory_estimate_records.json b/tests/data/memory_estimate_records.json index a8aa1931a..cabfb87e0 100644 --- a/tests/data/memory_estimate_records.json +++ b/tests/data/memory_estimate_records.json @@ -3,8 +3,8 @@ "0": { "arch_source": "/config.json", "calibrated": false, - "colocated": true, - "dp": 8, + "colocated": false, + "dp": 4, "estimated": true, "fits": true, "gpu": "H100", @@ -20,12 +20,11 @@ "grads_optimizer": 9.757, "inference": 0.0, "logits_block": 1.159, - "rollout_phase_extra": 5.239, "weights": 1.22 }, - "peak_gib": 36.642, + "peak_gib": 31.403, "pp": 1, - "rollout_phase_gib": 36.642, + "rollout_phase_gib": 0.0, "tokens": 4096, "tp": 1, "train_phase_gib": 31.403, @@ -34,8 +33,8 @@ "1": { "arch_source": "/config.json", "calibrated": false, - "colocated": true, - "dp": 8, + "colocated": false, + "dp": 4, "estimated": true, "fits": true, "gpu": "H100", @@ -51,12 +50,11 @@ "grads_optimizer": 9.757, "inference": 0.0, "logits_block": 1.159, - "rollout_phase_extra": 5.239, "weights": 1.22 }, - "peak_gib": 36.642, + "peak_gib": 31.403, "pp": 1, - "rollout_phase_gib": 36.642, + "rollout_phase_gib": 0.0, "tokens": 4096, "tp": 1, "train_phase_gib": 31.403, diff --git a/tests/test_exact_option_names.py b/tests/test_exact_option_names.py new file mode 100644 index 000000000..724d8b6cf --- /dev/null +++ b/tests/test_exact_option_names.py @@ -0,0 +1,129 @@ +"""yeto's parsers take long options by their full name only (``yeto.exact_argparse``). + +argparse's default prefix matching let a misspelled option set another one without +a word: ``yeto launch --rollout-num-gpus 8`` set ``--rollout-num-gpus-per-engine``. +A prefix is refused now, the error names the options probably meant, and the flags +yeto passes on to Miles are untouched. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import pytest + +from yeto import cli +from yeto.exact_argparse import ExactArgumentParser, suggestions +from yeto.launch.nc import cli as nc_cli +from yeto.rl.adapters.miles import config as miles_config +from yeto.rl.adapters.miles import island_entry + +REPO = Path(__file__).resolve().parents[1] +LAUNCH = ["launch", "--model", "m", "--data", "d", "--training-mode", "rl"] + + +def _error(capsys, parse, argv) -> str: + with pytest.raises(SystemExit) as exc: + parse(argv) + assert exc.value.code == 2 + return capsys.readouterr().err + + +def _parsers(parser: argparse.ArgumentParser, path=("yeto",)): + yield " ".join(path), parser + for action in parser._actions: + if isinstance(action, argparse._SubParsersAction): + for name, sub in action.choices.items(): + yield from _parsers(sub, (*path, name)) + + +def test_every_yeto_command_takes_full_option_names_only(): + seen = dict(_parsers(cli.build_parser())) + assert {"yeto launch", "yeto run up", "yeto fleet show", "yeto cluster probe", "yeto rollout scale", + "yeto breaker check", "yeto preflight"} <= set(seen) + assert [name for name, parser in seen.items() if parser.allow_abbrev] == [] + assert island_entry.build_parser().allow_abbrev is False + + +def test_a_launch_prefix_is_refused_and_the_meant_options_are_named(capsys): + err = _error(capsys, cli.build_parser().parse_args, [*LAUNCH, "--rollout-num-gpus", "8"]) + assert "unrecognized arguments: --rollout-num-gpus 8" in err + hint = next(line for line in err.splitlines() if line.strip().startswith("--rollout-num-gpus:")) + # the option with that destination first, then the one the prefix used to pick + assert hint.index("--rl-rollout-gpus") < hint.index("--rollout-num-gpus-per-engine") + # through main() (the `yeto` entry point) too, and with --opt=value + err = _error(capsys, cli.main, [*LAUNCH, "--rl-max-policy=2"]) + assert "unrecognized arguments: --rl-max-policy=2" in err and "--rl-max-policy-age" in err + + +def test_a_misspelling_gets_the_closest_spelling(capsys): + err = _error(capsys, cli.build_parser().parse_args, [*LAUNCH, "--rl-max-polcy-age", "2"]) + assert "did you mean --rl-max-policy-age" in err + + +def test_full_names_parse_as_before(): + args = cli.build_parser().parse_args([*LAUNCH, "--rollout-num-gpus-per-engine", "4", "--rl-rollout-gpus", "8", + "--rl-max-policy-age=3"]) + assert (args.rollout_num_gpus_per_engine, args.rollout_num_gpus, args.rl_max_policy_age) == (4, 8, 3) + legacy = cli.parse_args(["--model", "m", "--data", "d", "--rl-rollout-gpus", "2"]) + assert legacy.rollout_num_gpus == 2 + with pytest.raises(SystemExit): + cli.parse_args(["--model", "m", "--data", "d", "--rollout-num-gpus", "2"]) + + +def test_a_subcommand_hint_comes_from_that_subcommand(capsys): + err = _error(capsys, cli.build_parser().parse_args, ["fleet", "show", "--config", "c.json", "--gen", "3"]) + assert "--gen: options are taken by their full name; did you mean --generation?" in err + err = _error(capsys, nc_cli.main, ["pool", "--config", "pool.json", "--dry"]) + assert "unrecognized arguments: --dry" in err and "did you mean --dry-run" in err + + +def test_short_options_still_combine(): + parser = ExactArgumentParser(prog="t") + parser.add_argument("-v", action="store_true") + parser.add_argument("-x", action="store_true") + parser.add_argument("-n", type=int) + parser.add_argument("--name-long") + assert vars(parser.parse_args(["-vxn3"])) == {"v": True, "x": True, "n": 3, "name_long": None} + assert vars(parser.parse_args(["-vx", "-n", "4", "--name-long=a"]))["n"] == 4 + with pytest.raises(SystemExit): + parser.parse_args(["--name", "a"]) + export = cli.build_parser().parse_args(["dashboard", "export", "-o", "out.html"]) + assert export.out == "out.html" + + +def test_suggestions_are_bounded_and_skip_unrelated_names(): + parser = ExactArgumentParser(prog="t") + for i in range(8): + parser.add_argument(f"--alpha-{i}") + parser.add_argument("--zeta") + hints = suggestions("--alpha", [parser]) + assert len(hints) == 4 and all(h.startswith("--alpha-") for h in hints) + assert suggestions("--qqqqqqqq", [parser]) == [] + + +def test_the_customer_launch_argv_and_its_miles_flags_pass_through(): + argv = json.loads((REPO / "tests/fixtures/k31_customer_kit/run.json").read_text())["trainer"]["argv"] + args = cli.build_parser().parse_args(["launch", *argv]) + given = [a for a in argv if a.startswith(miles_config.TRAIN_EXTRA_ENV + "=")] + extra = [e for e in (*args.island_env, *args.modal_env) if e.startswith(miles_config.TRAIN_EXTRA_ENV + "=")] + assert len(given) == 1 and extra == given + # the Miles flags are a value to yeto: Miles gets them as written + raw = extra[0].split("=", 1)[1] + assert miles_config.train_extra_argv("kimi_k31", raw) == tuple(raw.split()) + + +def test_the_miles_island_refuses_a_prefix_and_keeps_miles_flags(tmp_path, monkeypatch, capsys): + from test_agentic_stage3_island_argv import _island_argv, _miles_argv + + full = _island_argv(tmp_path) + err = _error(capsys, island_entry.parse_args, [*full, "--rl-max-policy", "1"]) + assert "unrecognized arguments: --rl-max-policy 1" in err and "--rl-max-policy-age" in err + args = island_entry.parse_args(full) + miles = _miles_argv(args, tmp_path, monkeypatch) + # Miles' own option names, rendered in full for Miles' parser + for flag in ("--rollout-num-gpus-per-engine", "--rollout-batch-size", "--n-samples-per-prompt", + "--custom-generate-function-path"): + assert flag in miles diff --git a/tests/test_memory_estimate_sampler.py b/tests/test_memory_estimate_sampler.py index 01ef086af..22438a8f4 100644 --- a/tests/test_memory_estimate_sampler.py +++ b/tests/test_memory_estimate_sampler.py @@ -45,7 +45,7 @@ ("--tuning", "lora", "--rl-sync-preset", "strict-avg"), (0, 1)), ("full_parameter_fixed_partition", "qwen3_0p6b", "modal:1x8xh100,modal:1x8xh100", ("--tuning", "full", "--rl-sync-preset", "full-parameter", "--rl-placement", "fixed-partition", - "--rollout-num-gpus", "4"), (0, 1)), + "--rl-rollout-gpus", "4"), (0, 1)), ("pair_trainer", "qwen3_8b", "modal:1x8xh100,modal:1x8xh100", ("--tuning", "lora", "--rl-single-island-no-sync", "--rl-island-sample-role", "0:sampler", "--rl-island-sample-role", "1:trainer"), (1,)), diff --git a/yeto/cli.py b/yeto/cli.py index ec70c1299..793ebe970 100644 --- a/yeto/cli.py +++ b/yeto/cli.py @@ -30,6 +30,7 @@ import time from . import runs +from .exact_argparse import ExactArgumentParser from .losses import LOSS_FUNCTIONS from .rl.engine.run_flags import CLI, add_rl_flags from .launch.syncer_region import default_syncer_region @@ -848,7 +849,7 @@ def int_or_auto(value: str): def parse_args(argv=None): """Parse launch flags only (kept for callers that predate subcommands).""" - p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p = ExactArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) _add_launch_args(p) return p.parse_args(argv) @@ -947,7 +948,9 @@ def _add_local_rl_args(p: argparse.ArgumentParser) -> None: def build_parser() -> argparse.ArgumentParser: - p = argparse.ArgumentParser( + # full option names only (sub-parsers inherit the class): a prefix such as + # --rollout-num-gpus never silently sets --rollout-num-gpus-per-engine + p = ExactArgumentParser( prog="yeto", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, diff --git a/yeto/exact_argparse.py b/yeto/exact_argparse.py new file mode 100644 index 000000000..92976ac05 --- /dev/null +++ b/yeto/exact_argparse.py @@ -0,0 +1,93 @@ +"""Argument parsers that take long options by their full name only. + +argparse's default ``allow_abbrev=True`` resolves any unambiguous prefix of a +long option to that option, so a misspelled name can set a different option +without a word: ``yeto launch --rollout-num-gpus 8`` used to set +``--rollout-num-gpus-per-engine`` (the dedicated rollout GPUs are +``--rl-rollout-gpus``). :class:`ExactArgumentParser` turns abbreviations off +(sub-parsers inherit the class) and, when an option is not recognized, names +the options that were probably meant. + +Short options are unaffected: ``allow_abbrev=False`` only stops prefix matching +of long options; combined single-dash flags (``-vx``) still parse. +""" + +from __future__ import annotations + +import argparse +import difflib +import sys +from collections.abc import Sequence + +MAX_SUGGESTIONS = 4 + + +class ExactArgumentParser(argparse.ArgumentParser): + """``argparse.ArgumentParser`` with ``allow_abbrev=False`` and suggestions for + an unrecognized option. ``add_subparsers`` makes its sub-parsers of this class.""" + + def __init__(self, *args, allow_abbrev: bool = False, **kwargs): + super().__init__(*args, allow_abbrev=allow_abbrev, **kwargs) + + def parse_args(self, args=None, namespace=None): + argv = list(sys.argv[1:] if args is None else args) + parsed, extras = self.parse_known_args(argv, namespace) + if extras: + self.error(unrecognized_message(self, argv, extras)) + return parsed + + +def _sub_parsers(parser: argparse.ArgumentParser) -> dict[str, argparse.ArgumentParser]: + for action in parser._actions: # noqa: SLF001 - argparse has no public lookup + if isinstance(action, argparse._SubParsersAction): # noqa: SLF001 + return action.choices + return {} + + +def command_path(parser: argparse.ArgumentParser, argv: Sequence[str]) -> list[argparse.ArgumentParser]: + """``parser`` and the sub-parsers ``argv`` selects, outermost first.""" + path = [parser] + for token in argv: + choices = _sub_parsers(path[-1]) + if not choices: + break + if token in choices: + path.append(choices[token]) + return path + + +def suggestions(token: str, parsers: Sequence[argparse.ArgumentParser]) -> list[str]: + """Options of ``parsers`` that ``token`` (an unrecognized option) probably meant: + an option with the same destination, the options it is a prefix of (what an + abbreviation used to pick), then the closest spellings (difflib).""" + name = token.split("=", 1)[0] + options: dict[str, argparse.Action] = {} + for parser in parsers: + options.update(parser._option_string_actions) # noqa: SLF001 + long_options = [o for o in options if o.startswith("--")] + dest = name.lstrip("-").replace("-", "_") + same_dest = sorted({o for o in long_options if options[o].dest == dest}) + extends = sorted(o for o in long_options if o.startswith(name) and o != name) + close = difflib.get_close_matches(name, long_options, n=MAX_SUGGESTIONS, cutoff=0.6) + out: list[str] = [] + for option in (*same_dest, *extends, *close): + if option not in out: + out.append(option) + return out[:MAX_SUGGESTIONS] + + +def unrecognized_message(parser: argparse.ArgumentParser, argv: Sequence[str], + extras: Sequence[str]) -> str: + """argparse's ``unrecognized arguments: ...`` plus, for each unrecognized long + option, the options it probably meant.""" + lines = [f"unrecognized arguments: {' '.join(extras)}"] + parsers = command_path(parser, argv) + for token in extras: + if not token.startswith("--") or token == "--": + continue + hints = suggestions(token, parsers) + name = token.split("=", 1)[0] + if hints: + lines.append(f" {name}: options are taken by their full name; did you mean " + f"{', '.join(hints)}?") + return "\n".join(lines) diff --git a/yeto/launch/nc/cli.py b/yeto/launch/nc/cli.py index 022e87dcc..b588f7831 100644 --- a/yeto/launch/nc/cli.py +++ b/yeto/launch/nc/cli.py @@ -41,6 +41,7 @@ from pathlib import Path from typing import Any +from ... import exact_argparse from .. import agentic_setup from ..pool import status as island_status from ..pool.island_pool import Member @@ -1328,7 +1329,7 @@ def agentic_setup_cmd(args) -> int: # -- entry ------------------------------------------------------------------- def main(argv: list[str] | None = None, *, prog: str = "python -m yeto.launch.nc") -> int: - p = argparse.ArgumentParser(prog=prog, + p = exact_argparse.ExactArgumentParser(prog=prog, # full option names only description="National Compute nodes for yeto samplers (docs/NC_POOL.md). A lease " "is NOT ended at lease_until: a node stays billed until it is deleted.") sub = p.add_subparsers(dest="cmd", required=True) diff --git a/yeto/launch/rl_args.py b/yeto/launch/rl_args.py index f1e6c473e..da98c37b2 100644 --- a/yeto/launch/rl_args.py +++ b/yeto/launch/rl_args.py @@ -112,8 +112,9 @@ def _adopt_contract_settings(args, adopted: dict, *, source: str) -> None: import argparse from ..cli import _add_launch_args + from ..exact_argparse import ExactArgumentParser - parser = argparse.ArgumentParser() + parser = ExactArgumentParser() _add_launch_args(parser) conflicts = [] for dest, value in adopted.items(): diff --git a/yeto/rl/adapters/miles/island_entry.py b/yeto/rl/adapters/miles/island_entry.py index 4df0dab39..837463d88 100644 --- a/yeto/rl/adapters/miles/island_entry.py +++ b/yeto/rl/adapters/miles/island_entry.py @@ -44,7 +44,10 @@ def build_parser() -> argparse.ArgumentParser: from yeto.rl.adapters.miles.elastic_hook import add_recommend_arguments from yeto.wandb_logger import add_arguments as add_wandb_arguments - parser = argparse.ArgumentParser(prog="python3 -m yeto.rl.adapters.miles.island_entry") + from yeto.exact_argparse import ExactArgumentParser + + # full option names only: the launcher renders every island flag spelled out + parser = ExactArgumentParser(prog="python3 -m yeto.rl.adapters.miles.island_entry") add_rl_flags(parser, ISLAND) # yeto/rl/engine/run_flags.py add_recommend_arguments(parser) # elastic hook add_wandb_arguments(parser) diff --git a/yeto/rl/engine/run_flags.py b/yeto/rl/engine/run_flags.py index f24fbb652..8e6efe844 100644 --- a/yeto/rl/engine/run_flags.py +++ b/yeto/rl/engine/run_flags.py @@ -485,8 +485,7 @@ def rl_forward_pairs(*dests: str | tuple[str, str]) -> tuple[tuple[str, str], .. default=None, help="ports fixed partition: dedicated rollout GPUs per island (" "on a multi-node island the island total, laid out after the trainer's nodes). " - "Note: on `launch`, a bare --rollout-num-gpus is an argparse abbreviation of " - "--rollout-num-gpus-per-engine, not this option", + "`launch` takes no --rollout-num-gpus (options are taken by their full name)", ), shared_flag( "--rl-standby-gpus", From 45eef9d844ea367490921db3fe245d358b3ac597 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 23:33:10 +0800 Subject: [PATCH 2/3] Spell out --rl-rollout-gpus in the convertible-pool refusal test The test passed --rollout-num-gpus 1, which the abbreviation turned into --rollout-num-gpus-per-engine 1, so the refusal it matched was "fixed partition needs --rollout-num-gpus >= 1" instead of the convertible-node colocation rule it is about. With the full name it hits that rule. Co-Authored-By: Claude Opus 5.5 --- tests/test_rl_convertible_pool_launch.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_rl_convertible_pool_launch.py b/tests/test_rl_convertible_pool_launch.py index e94a89ea2..467d72e9c 100644 --- a/tests/test_rl_convertible_pool_launch.py +++ b/tests/test_rl_convertible_pool_launch.py @@ -111,7 +111,7 @@ def test_pool_needs_lora_or_full_colocated_and_a_modal_volume_store(): # --tuning full is the K3.1 form of a convertible node (whole-checkpoint releases) assert _args(base=[("full" if t == "lora" else t) for t in POOL]).tuning == "full" with pytest.raises(Exception, match="colocated|fixed partition"): # engines on other GPUs: no handoff - _args(("--rl-placement", "fixed-partition", "--rollout-num-gpus", "1")) + _args(("--rl-placement", "fixed-partition", "--rl-rollout-gpus", "1")) args = _args() args.rl_checkpoint_store = "/tmp/store" with pytest.raises(SystemExit, match="modal-volume"): From 901ac76bd8c5e41720379d6499151f33c75d97ff Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 23:51:25 +0800 Subject: [PATCH 3/3] exact_argparse: keep argparse's parse_args as the entry point Hints are added in error() for the "unrecognized arguments" message, from the argv parse_known_args saw, instead of overriding parse_args. Code and tests that wrap argparse.ArgumentParser.parse_args (the guide command-line check, the island lr-schedule check) see every yeto parser again. Co-Authored-By: Claude Opus 5.5 --- yeto/exact_argparse.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/yeto/exact_argparse.py b/yeto/exact_argparse.py index 92976ac05..1b6740c22 100644 --- a/yeto/exact_argparse.py +++ b/yeto/exact_argparse.py @@ -29,12 +29,19 @@ class ExactArgumentParser(argparse.ArgumentParser): def __init__(self, *args, allow_abbrev: bool = False, **kwargs): super().__init__(*args, allow_abbrev=allow_abbrev, **kwargs) - def parse_args(self, args=None, namespace=None): + # argparse's own parse_args stays the entry point (it calls parse_known_args, then + # error() with "unrecognized arguments: ..."): only that message gains the hints. + def parse_known_args(self, args=None, namespace=None): argv = list(sys.argv[1:] if args is None else args) - parsed, extras = self.parse_known_args(argv, namespace) - if extras: - self.error(unrecognized_message(self, argv, extras)) - return parsed + parsed, extras = super().parse_known_args(argv, namespace) + self._exact_last_parse = (argv, list(extras)) + return parsed, extras + + def error(self, message): + argv, extras = getattr(self, "_exact_last_parse", ((), ())) + if extras and message == argparse._("unrecognized arguments: %s") % " ".join(extras): + message = unrecognized_message(self, argv, extras) + super().error(message) def _sub_parsers(parser: argparse.ArgumentParser) -> dict[str, argparse.ArgumentParser]: