Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix argparse default value bug #2526

Merged
merged 2 commits into from
Jul 9, 2020
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
28 changes: 24 additions & 4 deletions pytorch_lightning/trainer/trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -792,12 +792,32 @@ def _arg_default(x) -> Union[int, str]:
else:
return int(x)

@staticmethod
def parse_argparser(arg_parser: Union[ArgumentParser, Namespace]) -> Namespace:
@classmethod
def parse_argparser(cls, arg_parser: Union[ArgumentParser, Namespace]) -> Namespace:
"""Parse CLI arguments, required for custom bool types."""
args = arg_parser.parse_args() if isinstance(arg_parser, ArgumentParser) else arg_parser
args = {k: True if v is None else v for k, v in vars(args).items()}
return Namespace(**args)

types_default = {
arg: (arg_types, arg_default) for arg, arg_types, arg_default in cls.get_init_arguments_and_types()
}

modified_args = {}
for k, v in vars(args).items():
if k in types_default and v is None:
# We need to figure out if the None is due to using nargs="?" or if it comes from the default value
arg_types, arg_default = types_default[k]
if bool in arg_types and isinstance(arg_default, bool):
Comment on lines +806 to +809
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it took me awhile to understand it... :]

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, it gets a bit complicated. Took me a while to understand it as well :P

# Value has been passed as a flag => It is currently None, so we need to set it to True
# We always set to True, regardless of the default value.
# Users must pass False directly, but when passing nothing True is assumed.
# i.e. the only way to disable somthing that defaults to True is to use the long form:
# "--a_default_true_arg False" becomes False, while "--a_default_false_arg" becomes None,
# which then becomes True here.

v = True

modified_args[k] = v
return Namespace(**modified_args)

@classmethod
def from_argparse_args(cls, args: Union[Namespace, ArgumentParser], **kwargs) -> 'Trainer':
Expand Down
16 changes: 15 additions & 1 deletion tests/trainer/test_trainer_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,21 @@ def _raise():
pytest.param('--tpu_cores=8',
{'tpu_cores': 8}),
pytest.param("--tpu_cores=1,",
{'tpu_cores': '1,'})
{'tpu_cores': '1,'}),
pytest.param(
"",
{
# These parameters are marked as Optional[...] in Trainer.__init__, with None as default.
# They should not be changed by the argparse interface.
"min_steps": None,
"max_steps": None,
"log_gpu_memory": None,
"distributed_backend": None,
"weights_save_path": None,
"truncated_bptt_steps": None,
"resume_from_checkpoint": None,
"profiler": None,
}),
])
def test_argparse_args_parsing(cli_args, expected):
"""Test multi type argument with bool."""
Expand Down