Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 8 additions & 10 deletions tests/data/memory_estimate_records.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
"0": {
"arch_source": "<qwen3_0p6b>/config.json",
"calibrated": false,
"colocated": true,
"dp": 8,
"colocated": false,
"dp": 4,
"estimated": true,
"fits": true,
"gpu": "H100",
Expand All @@ -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,
Expand All @@ -34,8 +33,8 @@
"1": {
"arch_source": "<qwen3_0p6b>/config.json",
"calibrated": false,
"colocated": true,
"dp": 8,
"colocated": false,
"dp": 4,
"estimated": true,
"fits": true,
"gpu": "H100",
Expand All @@ -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,
Expand Down
129 changes: 129 additions & 0 deletions tests/test_exact_option_names.py
Original file line number Diff line number Diff line change
@@ -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
2 changes: 1 addition & 1 deletion tests/test_memory_estimate_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,)),
Expand Down
2 changes: 1 addition & 1 deletion tests/test_rl_convertible_pool_launch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"):
Expand Down
7 changes: 5 additions & 2 deletions yeto/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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,
Expand Down
100 changes: 100 additions & 0 deletions yeto/exact_argparse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
"""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)

# 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 = 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]:
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)
3 changes: 2 additions & 1 deletion yeto/launch/nc/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion yeto/launch/rl_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
5 changes: 4 additions & 1 deletion yeto/rl/adapters/miles/island_entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 1 addition & 2 deletions yeto/rl/engine/run_flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading