hf_argparser.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. # Copyright 2020 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import dataclasses
  15. import json
  16. import os
  17. import sys
  18. import types
  19. from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
  20. from copy import copy
  21. from enum import Enum
  22. from inspect import isclass
  23. from pathlib import Path
  24. from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints
  25. import yaml
  26. DataClass = NewType("DataClass", Any)
  27. DataClassType = NewType("DataClassType", Any)
  28. # From https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse
  29. def string_to_bool(v):
  30. if isinstance(v, bool):
  31. return v
  32. if v.lower() in ("yes", "true", "t", "y", "1"):
  33. return True
  34. elif v.lower() in ("no", "false", "f", "n", "0"):
  35. return False
  36. else:
  37. raise ArgumentTypeError(
  38. f"Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive)."
  39. )
  40. def make_choice_type_function(choices: list) -> Callable[[str], Any]:
  41. """
  42. Creates a mapping function from each choices string representation to the actual value. Used to support multiple
  43. value types for a single argument.
  44. Args:
  45. choices (list): List of choices.
  46. Returns:
  47. Callable[[str], Any]: Mapping function from string representation to actual value for each choice.
  48. """
  49. str_to_choice = {str(choice): choice for choice in choices}
  50. return lambda arg: str_to_choice.get(arg, arg)
  51. def HfArg(
  52. *,
  53. aliases: Union[str, List[str]] = None,
  54. help: str = None,
  55. default: Any = dataclasses.MISSING,
  56. default_factory: Callable[[], Any] = dataclasses.MISSING,
  57. metadata: dict = None,
  58. **kwargs,
  59. ) -> dataclasses.Field:
  60. """Argument helper enabling a concise syntax to create dataclass fields for parsing with `HfArgumentParser`.
  61. Example comparing the use of `HfArg` and `dataclasses.field`:
  62. ```
  63. @dataclass
  64. class Args:
  65. regular_arg: str = dataclasses.field(default="Huggingface", metadata={"aliases": ["--example", "-e"], "help": "This syntax could be better!"})
  66. hf_arg: str = HfArg(default="Huggingface", aliases=["--example", "-e"], help="What a nice syntax!")
  67. ```
  68. Args:
  69. aliases (Union[str, List[str]], optional):
  70. Single string or list of strings of aliases to pass on to argparse, e.g. `aliases=["--example", "-e"]`.
  71. Defaults to None.
  72. help (str, optional): Help string to pass on to argparse that can be displayed with --help. Defaults to None.
  73. default (Any, optional):
  74. Default value for the argument. If not default or default_factory is specified, the argument is required.
  75. Defaults to dataclasses.MISSING.
  76. default_factory (Callable[[], Any], optional):
  77. The default_factory is a 0-argument function called to initialize a field's value. It is useful to provide
  78. default values for mutable types, e.g. lists: `default_factory=list`. Mutually exclusive with `default=`.
  79. Defaults to dataclasses.MISSING.
  80. metadata (dict, optional): Further metadata to pass on to `dataclasses.field`. Defaults to None.
  81. Returns:
  82. Field: A `dataclasses.Field` with the desired properties.
  83. """
  84. if metadata is None:
  85. # Important, don't use as default param in function signature because dict is mutable and shared across function calls
  86. metadata = {}
  87. if aliases is not None:
  88. metadata["aliases"] = aliases
  89. if help is not None:
  90. metadata["help"] = help
  91. return dataclasses.field(metadata=metadata, default=default, default_factory=default_factory, **kwargs)
  92. class HfArgumentParser(ArgumentParser):
  93. """
  94. This subclass of `argparse.ArgumentParser` uses type hints on dataclasses to generate arguments.
  95. The class is designed to play well with the native argparse. In particular, you can add more (non-dataclass backed)
  96. arguments to the parser after initialization and you'll get the output back after parsing as an additional
  97. namespace. Optional: To create sub argument groups use the `_argument_group_name` attribute in the dataclass.
  98. """
  99. dataclass_types: Iterable[DataClassType]
  100. def __init__(self, dataclass_types: Union[DataClassType, Iterable[DataClassType]], **kwargs):
  101. """
  102. Args:
  103. dataclass_types:
  104. Dataclass type, or list of dataclass types for which we will "fill" instances with the parsed args.
  105. kwargs (`Dict[str, Any]`, *optional*):
  106. Passed to `argparse.ArgumentParser()` in the regular way.
  107. """
  108. # To make the default appear when using --help
  109. if "formatter_class" not in kwargs:
  110. kwargs["formatter_class"] = ArgumentDefaultsHelpFormatter
  111. super().__init__(**kwargs)
  112. if dataclasses.is_dataclass(dataclass_types):
  113. dataclass_types = [dataclass_types]
  114. self.dataclass_types = list(dataclass_types)
  115. for dtype in self.dataclass_types:
  116. self._add_dataclass_arguments(dtype)
  117. @staticmethod
  118. def _parse_dataclass_field(parser: ArgumentParser, field: dataclasses.Field):
  119. # Long-option strings are conventionlly separated by hyphens rather
  120. # than underscores, e.g., "--long-format" rather than "--long_format".
  121. # Argparse converts hyphens to underscores so that the destination
  122. # string is a valid attribute name. Hf_argparser should do the same.
  123. long_options = [f"--{field.name}"]
  124. if "_" in field.name:
  125. long_options.append(f"--{field.name.replace('_', '-')}")
  126. kwargs = field.metadata.copy()
  127. # field.metadata is not used at all by Data Classes,
  128. # it is provided as a third-party extension mechanism.
  129. if isinstance(field.type, str):
  130. raise RuntimeError(
  131. "Unresolved type detected, which should have been done with the help of "
  132. "`typing.get_type_hints` method by default"
  133. )
  134. aliases = kwargs.pop("aliases", [])
  135. if isinstance(aliases, str):
  136. aliases = [aliases]
  137. origin_type = getattr(field.type, "__origin__", field.type)
  138. if origin_type is Union or (hasattr(types, "UnionType") and isinstance(origin_type, types.UnionType)):
  139. if str not in field.type.__args__ and (
  140. len(field.type.__args__) != 2 or type(None) not in field.type.__args__
  141. ):
  142. raise ValueError(
  143. "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because"
  144. " the argument parser only supports one type per argument."
  145. f" Problem encountered in field '{field.name}'."
  146. )
  147. if type(None) not in field.type.__args__:
  148. # filter `str` in Union
  149. field.type = field.type.__args__[0] if field.type.__args__[1] is str else field.type.__args__[1]
  150. origin_type = getattr(field.type, "__origin__", field.type)
  151. elif bool not in field.type.__args__:
  152. # filter `NoneType` in Union (except for `Union[bool, NoneType]`)
  153. field.type = (
  154. field.type.__args__[0] if isinstance(None, field.type.__args__[1]) else field.type.__args__[1]
  155. )
  156. origin_type = getattr(field.type, "__origin__", field.type)
  157. # A variable to store kwargs for a boolean field, if needed
  158. # so that we can init a `no_*` complement argument (see below)
  159. bool_kwargs = {}
  160. if origin_type is Literal or (isinstance(field.type, type) and issubclass(field.type, Enum)):
  161. if origin_type is Literal:
  162. kwargs["choices"] = field.type.__args__
  163. else:
  164. kwargs["choices"] = [x.value for x in field.type]
  165. kwargs["type"] = make_choice_type_function(kwargs["choices"])
  166. if field.default is not dataclasses.MISSING:
  167. kwargs["default"] = field.default
  168. else:
  169. kwargs["required"] = True
  170. elif field.type is bool or field.type == Optional[bool]:
  171. # Copy the currect kwargs to use to instantiate a `no_*` complement argument below.
  172. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument
  173. bool_kwargs = copy(kwargs)
  174. # Hack because type=bool in argparse does not behave as we want.
  175. kwargs["type"] = string_to_bool
  176. if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
  177. # Default value is False if we have no default when of type bool.
  178. default = False if field.default is dataclasses.MISSING else field.default
  179. # This is the value that will get picked if we don't include --{field.name} in any way
  180. kwargs["default"] = default
  181. # This tells argparse we accept 0 or 1 value after --{field.name}
  182. kwargs["nargs"] = "?"
  183. # This is the value that will get picked if we do --{field.name} (without value)
  184. kwargs["const"] = True
  185. elif isclass(origin_type) and issubclass(origin_type, list):
  186. kwargs["type"] = field.type.__args__[0]
  187. kwargs["nargs"] = "+"
  188. if field.default_factory is not dataclasses.MISSING:
  189. kwargs["default"] = field.default_factory()
  190. elif field.default is dataclasses.MISSING:
  191. kwargs["required"] = True
  192. else:
  193. kwargs["type"] = field.type
  194. if field.default is not dataclasses.MISSING:
  195. kwargs["default"] = field.default
  196. elif field.default_factory is not dataclasses.MISSING:
  197. kwargs["default"] = field.default_factory()
  198. else:
  199. kwargs["required"] = True
  200. parser.add_argument(*long_options, *aliases, **kwargs)
  201. # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
  202. # Order is important for arguments with the same destination!
  203. # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
  204. # here and we do not need those changes/additional keys.
  205. if field.default is True and (field.type is bool or field.type == Optional[bool]):
  206. bool_kwargs["default"] = False
  207. parser.add_argument(
  208. f"--no_{field.name}",
  209. f"--no-{field.name.replace('_', '-')}",
  210. action="store_false",
  211. dest=field.name,
  212. **bool_kwargs,
  213. )
  214. def _add_dataclass_arguments(self, dtype: DataClassType):
  215. if hasattr(dtype, "_argument_group_name"):
  216. parser = self.add_argument_group(dtype._argument_group_name)
  217. else:
  218. parser = self
  219. try:
  220. type_hints: Dict[str, type] = get_type_hints(dtype)
  221. except NameError:
  222. raise RuntimeError(
  223. f"Type resolution failed for {dtype}. Try declaring the class in global scope or "
  224. "removing line of `from __future__ import annotations` which opts in Postponed "
  225. "Evaluation of Annotations (PEP 563)"
  226. )
  227. except TypeError as ex:
  228. # Remove this block when we drop Python 3.9 support
  229. if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(ex):
  230. python_version = ".".join(map(str, sys.version_info[:3]))
  231. raise RuntimeError(
  232. f"Type resolution failed for {dtype} on Python {python_version}. Try removing "
  233. "line of `from __future__ import annotations` which opts in union types as "
  234. "`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To "
  235. "support Python versions that lower than 3.10, you need to use "
  236. "`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of "
  237. "`X | None`."
  238. ) from ex
  239. raise
  240. for field in dataclasses.fields(dtype):
  241. if not field.init:
  242. continue
  243. field.type = type_hints[field.name]
  244. self._parse_dataclass_field(parser, field)
  245. def parse_args_into_dataclasses(
  246. self,
  247. args=None,
  248. return_remaining_strings=False,
  249. look_for_args_file=True,
  250. args_filename=None,
  251. args_file_flag=None,
  252. ) -> Tuple[DataClass, ...]:
  253. """
  254. Parse command-line args into instances of the specified dataclass types.
  255. This relies on argparse's `ArgumentParser.parse_known_args`. See the doc at:
  256. docs.python.org/3.7/library/argparse.html#argparse.ArgumentParser.parse_args
  257. Args:
  258. args:
  259. List of strings to parse. The default is taken from sys.argv. (same as argparse.ArgumentParser)
  260. return_remaining_strings:
  261. If true, also return a list of remaining argument strings.
  262. look_for_args_file:
  263. If true, will look for a ".args" file with the same base name as the entry point script for this
  264. process, and will append its potential content to the command line args.
  265. args_filename:
  266. If not None, will uses this file instead of the ".args" file specified in the previous argument.
  267. args_file_flag:
  268. If not None, will look for a file in the command-line args specified with this flag. The flag can be
  269. specified multiple times and precedence is determined by the order (last one wins).
  270. Returns:
  271. Tuple consisting of:
  272. - the dataclass instances in the same order as they were passed to the initializer.abspath
  273. - if applicable, an additional namespace for more (non-dataclass backed) arguments added to the parser
  274. after initialization.
  275. - The potential list of remaining argument strings. (same as argparse.ArgumentParser.parse_known_args)
  276. """
  277. if args_file_flag or args_filename or (look_for_args_file and len(sys.argv)):
  278. args_files = []
  279. if args_filename:
  280. args_files.append(Path(args_filename))
  281. elif look_for_args_file and len(sys.argv):
  282. args_files.append(Path(sys.argv[0]).with_suffix(".args"))
  283. # args files specified via command line flag should overwrite default args files so we add them last
  284. if args_file_flag:
  285. # Create special parser just to extract the args_file_flag values
  286. args_file_parser = ArgumentParser()
  287. args_file_parser.add_argument(args_file_flag, type=str, action="append")
  288. # Use only remaining args for further parsing (remove the args_file_flag)
  289. cfg, args = args_file_parser.parse_known_args(args=args)
  290. cmd_args_file_paths = vars(cfg).get(args_file_flag.lstrip("-"), None)
  291. if cmd_args_file_paths:
  292. args_files.extend([Path(p) for p in cmd_args_file_paths])
  293. file_args = []
  294. for args_file in args_files:
  295. if args_file.exists():
  296. file_args += args_file.read_text().split()
  297. # in case of duplicate arguments the last one has precedence
  298. # args specified via the command line should overwrite args from files, so we add them last
  299. args = file_args + args if args is not None else file_args + sys.argv[1:]
  300. namespace, remaining_args = self.parse_known_args(args=args)
  301. outputs = []
  302. for dtype in self.dataclass_types:
  303. keys = {f.name for f in dataclasses.fields(dtype) if f.init}
  304. inputs = {k: v for k, v in vars(namespace).items() if k in keys}
  305. for k in keys:
  306. delattr(namespace, k)
  307. obj = dtype(**inputs)
  308. outputs.append(obj)
  309. if len(namespace.__dict__) > 0:
  310. # additional namespace.
  311. outputs.append(namespace)
  312. if return_remaining_strings:
  313. return (*outputs, remaining_args)
  314. else:
  315. if remaining_args:
  316. raise ValueError(f"Some specified arguments are not used by the HfArgumentParser: {remaining_args}")
  317. return (*outputs,)
  318. def parse_dict(self, args: Dict[str, Any], allow_extra_keys: bool = False) -> Tuple[DataClass, ...]:
  319. """
  320. Alternative helper method that does not use `argparse` at all, instead uses a dict and populating the dataclass
  321. types.
  322. Args:
  323. args (`dict`):
  324. dict containing config values
  325. allow_extra_keys (`bool`, *optional*, defaults to `False`):
  326. Defaults to False. If False, will raise an exception if the dict contains keys that are not parsed.
  327. Returns:
  328. Tuple consisting of:
  329. - the dataclass instances in the same order as they were passed to the initializer.
  330. """
  331. unused_keys = set(args.keys())
  332. outputs = []
  333. for dtype in self.dataclass_types:
  334. keys = {f.name for f in dataclasses.fields(dtype) if f.init}
  335. inputs = {k: v for k, v in args.items() if k in keys}
  336. unused_keys.difference_update(inputs.keys())
  337. obj = dtype(**inputs)
  338. outputs.append(obj)
  339. if not allow_extra_keys and unused_keys:
  340. raise ValueError(f"Some keys are not used by the HfArgumentParser: {sorted(unused_keys)}")
  341. return tuple(outputs)
  342. def parse_json_file(
  343. self, json_file: Union[str, os.PathLike], allow_extra_keys: bool = False
  344. ) -> Tuple[DataClass, ...]:
  345. """
  346. Alternative helper method that does not use `argparse` at all, instead loading a json file and populating the
  347. dataclass types.
  348. Args:
  349. json_file (`str` or `os.PathLike`):
  350. File name of the json file to parse
  351. allow_extra_keys (`bool`, *optional*, defaults to `False`):
  352. Defaults to False. If False, will raise an exception if the json file contains keys that are not
  353. parsed.
  354. Returns:
  355. Tuple consisting of:
  356. - the dataclass instances in the same order as they were passed to the initializer.
  357. """
  358. with open(Path(json_file), encoding="utf-8") as open_json_file:
  359. data = json.loads(open_json_file.read())
  360. outputs = self.parse_dict(data, allow_extra_keys=allow_extra_keys)
  361. return tuple(outputs)
  362. def parse_yaml_file(
  363. self, yaml_file: Union[str, os.PathLike], allow_extra_keys: bool = False
  364. ) -> Tuple[DataClass, ...]:
  365. """
  366. Alternative helper method that does not use `argparse` at all, instead loading a yaml file and populating the
  367. dataclass types.
  368. Args:
  369. yaml_file (`str` or `os.PathLike`):
  370. File name of the yaml file to parse
  371. allow_extra_keys (`bool`, *optional*, defaults to `False`):
  372. Defaults to False. If False, will raise an exception if the json file contains keys that are not
  373. parsed.
  374. Returns:
  375. Tuple consisting of:
  376. - the dataclass instances in the same order as they were passed to the initializer.
  377. """
  378. outputs = self.parse_dict(yaml.safe_load(Path(yaml_file).read_text()), allow_extra_keys=allow_extra_keys)
  379. return tuple(outputs)