tyro: Allowing a 'default subcommand value' for a custom constructor which returns a Union
Hi! I have the following use-case:
# tyro_ex.py
from dataclasses import dataclass
from typing import Annotated, Union
import tyro
@dataclass(frozen=True)
class OptimizerConfig:
lr: float = 1e-1
@dataclass(frozen=True)
class AdamConfig(OptimizerConfig):
adam_foo: float = 1.0
@dataclass(frozen=True)
class SGDConfig(OptimizerConfig):
sgd_foo: float = 1.0
def _constructor() -> type[OptimizerConfig]:
cfgs = [
Annotated[AdamConfig, tyro.conf.subcommand(name="adam")],
Annotated[SGDConfig, tyro.conf.subcommand(name="sgd")],
]
return Union[*cfgs] # type: ignore
@dataclass
class Config:
optimizer: Annotated[
AdamConfig | SGDConfig, tyro.conf.arg(constructor_factory=_constructor)
]
foo: int = 1
bar: str = "abc"
def main(cfg: Config):
print(cfg)
if __name__ == "__main__":
tyro.cli(main, config=(tyro.conf.ConsolidateSubcommandArgs,))
py tyro_ex.py --help will force me to choose a subcommand (great):
usage: tyro_ex.py [-h] {cfg.optimizer:adam,cfg.optimizer:sgd}
╭─ options ─────────────────────────────────────────╮
│ -h, --help show this help message and exit │
╰───────────────────────────────────────────────────╯
╭─ subcommands ─────────────────────────────────────╮
│ {cfg.optimizer:adam,cfg.optimizer:sgd} │
│ cfg.optimizer:adam │
│ cfg.optimizer:sgd │
╰───────────────────────────────────────────────────╯
Once I choose an optimizer via a subcommand (py tyro_ex.py cfg.optimizer:adam --help), I can then manipulate (and get helptext for) the arguments of both the parent config, and the nested optimizer config:
usage: tyro_ex.py cfg.optimizer:adam [-h] [CFG.OPTIMIZER:ADAM OPTIONS]
╭─ options ────────────────────────────────────────────╮
│ -h, --help show this help message and exit │
╰──────────────────────────────────────────────────────╯
╭─ cfg.optimizer options ──────────────────────────────╮
│ --cfg.optimizer.lr FLOAT │
│ (default: 0.1) │
│ --cfg.optimizer.adam-foo FLOAT │
│ (default: 1.0) │
╰──────────────────────────────────────────────────────╯
╭─ cfg options ────────────────────────────────────────╮
│ --cfg.foo INT (default: 1) │
│ --cfg.bar STR (default: abc) │
╰──────────────────────────────────────────────────────╯
My question is, how to set a “default subcommand value” that can also possibly be changed? i.e. I’d like to be able to do something like:
@dataclass
class Config:
optimizer: Annotated[
AdamConfig | SGDConfig, tyro.conf.arg(constructor_factory=_constructor)
] = AdamConfig()
foo: int = 1
bar: str = "abc"
and if the user invokes py tyro_ex.py --help, the behaviour+helptext would be identical to the second example above (py tyro_ex.py cfg.optimizer:adam --help), but it would still be possible to choose a different optimizer config e.g. py tyro_ex.py cfg.optimizer:sgd --help should adapt the choice. The above case (= AdamConfg()) will still force me choose a subcommand (I assume due to the custom constructor). Things I’ve tried:
- using
tyro.conf.AvoidSubcommandsfor both theAdamConfig | SGDConfigunion, or the return of the_constructor. The constructors I’m working with are a bit more involved but having a solution even for this case would be great. - I assume it would be possible to just capture the cli call and modify the
sys.argvto appendcfg.optimizer:adameven when the user invokes onlypy tyro_ex.py --helphowever I would then still need a way to show to the user passing--helpthat thecfg.optimizeris still a choice which can be modified.
I don’t have a hard requirement for how the default is delivered. Preferably it would be either in the Config dataclass or the custom constructor, but any working solution would be a good starting point. I’m using constructor_factory since it’s possible the choices are dynamically modified by the user before tyro.cli is invoked (think a registry system of name: str -> OptimizerConfig where someone adds a custom optimizer, and then invokes the cli entrypoint).
I assume it should be clear from the docs already whether this is possible or not, but I wasn’t able to make it work - I assumed it was possible since py tyro_ex.py cfg.optimizer:adam --help does such a good job of propagating the options ‘post-command choice’ that it would make sense for a default command setting to allow the same behavior. Maybe it would be possible to open the ‘Discussions’ feature on the repo for questions like this? Thanks!
small additional question: is it possible to modify the title of a subcategory in the helptext? i.e. for py tyro_ex.py cfg.optimizer:adam --help as above, to have something like:
usage: tyro_ex.py cfg.optimizer:adam [-h] [CFG.OPTIMIZER:ADAM OPTIONS]
╭─ options ────────────────────────────────────────────╮
│ -h, --help show this help message and exit │
╰──────────────────────────────────────────────────────╯
╭─ CUSTOM_TITLE_HERE_ADAM_RELATED options ─────────────────────
│ --cfg.optimizer.lr FLOAT │
│ (default: 0.1) │
│ --cfg.optimizer.adam-foo FLOAT │
│ (default: 1.0) │
╰──────────────────────────────────────────────────────╯
╭─ cfg options ────────────────────────────────────────╮
│ --cfg.foo INT (default: 1) │
│ --cfg.bar STR (default: abc) │
╰──────────────────────────────────────────────────────╯
edit: The following also doesn’t work:
if __name__ == "__main__":
cfg = tyro.cli(
Config,
config=(tyro.conf.ConsolidateSubcommandArgs,),
default=Config(optimizer=AdamConfig()),
)
main(cfg)
I am still forced to choose an optimizer.
edit 2: Should this line say “… use tyro.confAvoidSubcommands[]”? https://github.com/brentyi/tyro/blob/17042845a18a6b12f22993e013f99d8715cde8ad/src/tyro/_cli.py#L286
About this issue
- Original URL
- State: open
- Created 2 years ago
- Comments: 20 (20 by maintainers)
Thanks again and sorry for the wild-goose chase! If you are curious (and maybe someone else has a similar use-case): this branch implements a work-in-progress solution for the original problem (that works for the use-case presented above; it also changes how columns are formatted to be less restrictive with min height requirements). I still need to figure out how to show the user the helptext for subcommand choices and add group subtitles.
The TL;DR of the approach is: rely on tyro’s
match_subcommandto identify the correct default_name for each subcommand which has a default.Collect all subparser default names from the tree in post-order fashion, propagating all the choices in visit order up to the rootParserSpecificationobject (https://github.com/mirceamironenco/tyro/blob/mircea_dev/src/tyro/_parsers.py#L196-L216). The reason being that this object is used in_cli.pywhere we have both the user args and now all of the default subcommand choices. We will need a way to match user arguments with possible choices for a subcommand. For this I am using a DSU singleton (probably overkill), and treating the choices as a connected component, so the user can specify e.g.optimizer:sgdand I know I am supposed to replace a defaultoptimizer:*(which can be any other choice). The DSU is built together with the ordered dict of choices. Then everything is used here: https://github.com/mirceamironenco/tyro/blob/mircea_dev/src/tyro/_cli.py#L392-L450, where after the parser_spec is constructed, we have the defaults and potentially replace them with the user choices.(Cannot promise this doesn’t have bugs. Also links to specific file lines in the comment above might not be valid as I’m still working on this.)
edit: Above solution could not deal with nested choices, and required installing from a different branch. The following is more robust and can be used as a patch on top of current tyro installation:
https://gist.github.com/mirceamironenco/b3c6f0e7a6c44f4de78007bd5a133b6e
I think if you want to hack this in it should be doable, but making it the default behavior might also be complicated:
optimizer:sgd, there’s no guarantee that theoptimizerargument group actually exists. For example, when:tyro.conf.OmitArgPrefixesis usedtyro.conf.OmitSubcommandPrefixesis usedSGDConfigdataclass, like ifsgdonly contains more subparsers or more nested dataclasses resulting in args like--optimizer.scheduler.learning-rate--optimizer.scheduler.*example, it can be more intuitive for the docstring to apply to all arguments displayed in the help message and not just theoptimizergroup.I think there’s probably some better API / set of default behaviors for displaying or configuring the helptext headings, it’s just a matter of balancing with complexity… does that answer your question?
I haven’t decided whether to merge, but could you see if #227 does what you’re looking for? The changes are small but there might also be bugs, the parser + subparser tree structures get complicated and (as you may have noticed) there are often edge cases I don’t think of.
Sorry for the opaqueness here, this unfortunately also isn’t configurable.
To explain the current behavior:
When you have
AvoidSubcommandsspecified we parse your example ~equivalently to, where the help string unambiguously applies to just the arguments of
AdamConfig. This is why the helptext will show up above the argument group.When you don’t have
AvoidSubcommands, we parse it ~equivalently to, where the help string applies to the union / subparser group as a whole. In this case, the helptext will show up above the subcommand list (in
python example.py --help) but not for just the arguments of AdamConfig (inpython example.py optimizer:adam-config --help).I don’t feel strongly about this design. The tradeoffs are relatively minor:
"""Configuration for the optimizer.“”")"""We support Adam and SGD optimizers.""written above the Adam arguments)Unfortunately I can’t think of a clean way to implement this without rewriting the
argparsebackend. I think this is plausible (especially given our increasingly comprehensive test suite) and I’d be interested, but it’d be a large undertaking. For the foreseeable future it seems like the subcommand verbosity will just need to be a tradeoff of theConsolidateSubcommandArgsflag.The second discrepancy you pointed out: this behavior makes sense, but not as much sense as
python tyro_ex.pyandpython tyro_ex.py optimizer:adambehaving the same whenoptimizer:adamis the default subcommand. I’ll fix this + add a note in the documentation.Thanks for helping me sort out all of these kinks…!
On this: unfortunately not! It’s hardcoded here:
https://github.com/brentyi/tyro/blob/17042845a18a6b12f22993e013f99d8715cde8ad/src/tyro/_parsers.py#L241-L249
Hi @mirceamironenco!
Yeah, this is working as-designed but I do agree that what you’ve described would be ideal.
We currently set all subcommands to required when
tyro.conf.ConsolidateSubcommandArgsis passed in:https://github.com/brentyi/tyro/blob/17042845a18a6b12f22993e013f99d8715cde8ad/src/tyro/_parsers.py#L600-L602
It’s also in the tests:
https://github.com/brentyi/tyro/blob/17042845a18a6b12f22993e013f99d8715cde8ad/tests/test_conf.py#L833-L835
And hinted at in the docs (“at the cost of support for optional subcommands”), although I can see that this is vague:
https://github.com/brentyi/tyro/blob/17042845a18a6b12f22993e013f99d8715cde8ad/src/tyro/conf/_markers.py#L65-L67
I’m looking into relaxing this, which seems simple but is actually a little bit tricky (this was part of the reason for the current design). If we visualize the possible subcommands as a tree:
I can get back (hopefully today) once I’ve made some progress!