Debian Codegraph @

ml_collections/config_flags/config_flags.py

raw symbols SCIP
1 # Copyright 2024 The ML Collections Authors.
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
15 """Configuration commmand line parser."""
16
17 import ast
18 import copy
19 import dataclasses
20 import enum
21 import errno
22 import functools as ft
23 import importlib.machinery
24 import os
25 import re
26 import sys
27 import traceback
28 import types
29 from typing import Any, Callable, Dict, Generic, List, MutableMapping, Optional, Sequence, Tuple, Type, TypeVar
30
31 from absl import flags
32 from absl import logging
33 from ml_collections import config_dict
34 from ml_collections.config_flags import config_path
35 from ml_collections.config_flags import tuple_parser
36
37 FLAGS = flags.FLAGS
38
39 # Forward for backwards compatibility.
40 GetValue = config_path.get_value
41 GetType = config_path.get_type
42 SetValue = config_path.set_value
43
44 # Any flags defined via any of the config_flags.DEFINE_config_*() functions
45 # should be attributed to the caller of that function rather than this module.
46 flags.disclaim_key_flags()
47
48
49 def _load_source(module_name: str, module_path: str) -> types.ModuleType:
50 """Loads a Python module from its source file.
51
52 Args:
53 module_name: name of the module in sys.modules.
54 module_path: path to the Python file containing the module.
55
56 Returns:
57 The loaded Python module.
58 """
59 loader = importlib.machinery.SourceFileLoader(module_name, module_path)
60 return loader.load_module()
61
62
63 class _LiteralParser(flags.ArgumentParser):
64 """Parse arbitrary built-in (`--cfg.val=1`, `--cfg.val="[1, 2, {}]"`,...)."""
65
66 def parse(self, argument: str) -> Any:
67 # _LiteralParser cannot know in advance what is the expected type.
68 # The default value is never passed, as default is overwritten to `None`
69 # bellow inside `_ConfigFlag._parse`.
70 if not isinstance(argument, str):
71 raise TypeError('argument should be a string')
72 # Absl hardcode bool values as lower-case: `--cfg.my_bool`, so convert
73 # them to Python built-in
74 if argument in ('true', 'false'):
75 argument = argument.capitalize()
76 try:
77 return ast.literal_eval(argument)
78 except (SyntaxError, ValueError):
79 # Otherwise, the flag is a string: `--cfg.value="my_string"`
80 return argument
81
82 def flag_type(self):
83 return 'config_literal'
84
85
86 class _ConfigDictParser(flags.ArgumentParser):
87 """Parser for ConfigDict values."""
88
89 def parse(self, argument: str) -> config_dict.ConfigDict:
90 try:
91 value = ast.literal_eval(argument)
92 except (SyntaxError, ValueError) as e:
93 raise ValueError(
94 f'Failed to parse {argument!r} as a ConfigDict: {e!r}'
95 ) from None
96
97 if not isinstance(value, dict):
98 raise ValueError(
99 f'Failed to parse {argument!r} as a ConfigDict: `{value!r}` is not a'
100 ' dict.'
101 )
102 return config_dict.ConfigDict(value)
103
104
105 _FIELD_TYPE_TO_PARSER = {
106 float: flags.FloatParser(),
107 bool: flags.BooleanParser(),
108 tuple: tuple_parser.TupleParser(),
109 int: flags.IntegerParser(),
110 str: flags.ArgumentParser(),
111 config_dict.ConfigDict: _ConfigDictParser(),
112 object: _LiteralParser(),
113 }
114
115
116 class UnsupportedOperationError(flags.Error):
117 pass
118
119
120 class FlagOrderError(flags.Error):
121 pass
122
123
124 class UnparsedFlagError(flags.Error):
125 pass
126
127
128 def DEFINE_config_file( # pylint: disable=g-bad-name
129 name: str,
130 default: Optional[str] = None,
131 help_string: str = 'path to config file.',
132 flag_values: flags.FlagValues = FLAGS,
133 lock_config: bool = True,
134 accept_new_attributes: bool = False,
135 sys_argv: Optional[List[str]] = None,
136 **kwargs) -> flags.FlagHolder:
137 r"""Defines flag for `ConfigDict` files compatible with absl flags.
138
139 The flag's value should be a path to a valid python file which contains a
140 function called `get_config()` that returns a python object specifying
141 a configuration. After the flag is parsed, `FLAGS.name` will contain
142 a reference to this object, optionally with some values overridden.
143
144 During flags parsing, every flag of form `--name.([a-zA-Z0-9]+\.?)+=value`
145 and `-name.([a-zA-Z0-9]+\.?)+ value` will be treated as an override of a
146 specific field in the config object returned by this flag. Field is
147 essentially a dot delimited path inside the object where each path element
148 has to be either an attribute or a key existing in the config object.
149 For example `--my_config.field1.field2=val` means "assign value val
150 to the attribute (or key) `field2` inside value of the attribute (or key)
151 `field1` inside the value of `my_config` object". If there are both
152 attribute and key-based access with the same name, attribute is preferred.
153
154 Typical usage example:
155
156 `script.py`::
157
158 from ml_collections import config_flags
159
160 _CONFIG = config_flags.DEFINE_config_file('my_config')
161
162 print(_CONFIG.value)
163
164 `config.py`::
165
166 def get_config():
167 return {
168 'field1': 1,
169 'field2': 'tom',
170 'nested': {
171 'field': 2.23,
172 },
173 }
174
175 The following command::
176
177 python script.py -- --my_config=config.py
178 --my_config.field1 8
179 --my_config.nested.field=2.1
180
181 will print::
182
183 {'field1': 8, 'field2': 'tom', 'nested': {'field': 2.1}}
184
185 It is possible to parameterise the get_config function, allowing it to
186 return a differently structured result for different occasions. This is
187 particularly useful when setting up hyperparameter sweeps across various
188 network architectures.
189
190 `parameterised_config.py`::
191
192 def get_config(config_string):
193 possible_configs = {
194 'mlp': {
195 'constructor': 'snt.nets.MLP',
196 'config': {
197 'output_sizes': (128, 128, 1),
198 }
199 },
200 'lstm': {
201 'constructor': 'snt.LSTM',
202 'config': {
203 'hidden_size': 128,
204 'forget_bias': 1.0,
205 }
206 }
207 }
208 return possible_configs[config_string]
209
210 If a colon is present in the command line override for the config file,
211 everything to the right of the colon is passed into the get_config function.
212 The following command lines will both function correctly::
213
214 python script.py -- --my_config=parameterised_config.py:mlp
215 --my_config.config.output_sizes="(256,256,1)"
216
217
218 python script.py -- --my_config=parameterised_config.py:lstm
219 --my_config.config.hidden_size=256
220
221 The following will produce an error, as the hidden_size flag does not
222 exist when the "mlp" config_string is provided::
223
224 python script.py -- --my_config=parameterised_config.py:mlp
225 --my_config.config.hidden_size=256
226
227 Args:
228 name: Flag name, optionally including extra config after a colon.
229 default: Default value of the flag (default: None).
230 help_string: Help string to display when --helpfull is called. (default:
231 "path to config file.")
232 flag_values: FlagValues instance used for parsing. (default:
233 absl.flags.FLAGS)
234 lock_config: If set to True, loaded config will be locked through calling
235 .lock() method on its instance (if it exists). (default: True)
236 accept_new_attributes: If `True`, accept to pass arbitrary attributes that
237 are not originally defined in the `get_config()` dict.
238 `accept_new_attributes` requires `lock_config=False`.
239 sys_argv: If set, interprets this as the full list of args used in parsing.
240 This is used to identify which overrides to define as flags. If not
241 specified, uses the system sys.argv to figure it out.
242 **kwargs: Optional keyword arguments passed to Flag constructor.
243
244 Returns:
245 a handle to defined flag.
246 """
247 if accept_new_attributes and lock_config:
248 raise ValueError('`accept_new_attributes=True` requires lock_config=False')
249 parser = ConfigFileFlagParser(name=name, lock_config=lock_config)
250 serializer = flags.ArgumentSerializer()
251 flag = _ConfigFlag(
252 parser=parser,
253 serializer=serializer,
254 name=name,
255 default=default,
256 help_string=help_string,
257 flag_values=flag_values,
258 accept_new_attributes=accept_new_attributes,
259 sys_argv=sys_argv,
260 **kwargs)
261
262 return flags.DEFINE_flag(flag, flag_values)
263
264
265 def DEFINE_config_dict( # pylint: disable=g-bad-name
266 name: str,
267 config: config_dict.ConfigDict,
268 help_string: str = 'ConfigDict instance.',
269 flag_values: flags.FlagValues = FLAGS,
270 lock_config: bool = True,
271 accept_new_attributes: bool = False,
272 sys_argv: Optional[List[str]] = None,
273 **kwargs) -> flags.FlagHolder:
274 """Defines flag for inline `ConfigDict's` compatible with absl flags.
275
276 Similar to `DEFINE_config_file` except the flag's value should be a
277 `ConfigDict` instead of a path to a file containing a `ConfigDict`. After the
278 flag is parsed, `FLAGS.name` will contain a reference to the `ConfigDict`,
279 optionally with some values overridden.
280
281 Typical usage example:
282
283 `script.py`::
284
285 from ml_collections import config_dict
286 from ml_collections import config_flags
287
288
289 config = config_dict.ConfigDict({
290 'field1': 1,
291 'field2': 'tom',
292 'nested': {
293 'field': 2.23,
294 }
295 })
296
297
298 _CONFIG = config_flags.DEFINE_config_dict('my_config', config)
299 ...
300
301 print(_CONFIG.value)
302
303 The following command::
304
305 python script.py -- --my_config.field1 8
306 --my_config.nested.field=2.1
307
308 will print::
309
310 field1: 8
311 field2: tom
312 nested: {field: 2.1}
313
314 Args:
315 name: Flag name.
316 config: `ConfigDict` object.
317 help_string: Help string to display when --helpfull is called.
318 (default: "ConfigDict instance.")
319 flag_values: FlagValues instance used for parsing.
320 (default: absl.flags.FLAGS)
321 lock_config: If set to True, loaded config will be locked through calling
322 .lock() method on its instance (if it exists). (default: True)
323 accept_new_attributes: If `True`, accept to pass arbitrary attributes that
324 are not originally defined in the `config` argument.
325 `accept_new_attributes` requires `lock_config=False`.
326 sys_argv: If set, interprets this as the full list of args used in parsing.
327 This is used to identify which overrides to define as flags. If not
328 specified, uses the system sys.argv to figure it out.
329 **kwargs: Optional keyword arguments passed to Flag constructor.
330
331 Returns:
332 a handle to defined flag.
333 """
334 if not isinstance(config, config_dict.ConfigDict):
335 raise TypeError('config should be a ConfigDict')
336 if accept_new_attributes and lock_config:
337 raise ValueError('`accept_new_attributes=True` requires lock_config=False')
338 parser = _InlineConfigParser(name=name, lock_config=lock_config)
339 flag = _ConfigFlag(
340 parser=parser,
341 serializer=flags.ArgumentSerializer(),
342 name=name,
343 default=config,
344 help_string=help_string,
345 flag_values=flag_values,
346 accept_new_attributes=accept_new_attributes,
347 sys_argv=sys_argv,
348 **kwargs)
349
350 # Get the module name for the frame at depth 1 in the call stack.
351 module_name = sys._getframe(1).f_globals.get('__name__', None) # pylint: disable=protected-access
352 module_name = sys.argv[0] if module_name == '__main__' else module_name
353 return flags.DEFINE_flag(flag, flag_values, module_name=module_name)
354
355
356 # Note that we would add a bound to constrain this to be a dataclass, except
357 # that dataclasses don't have a specific base class, and structural typing for
358 # attributes is currently (2021Q1) not supported in pytype (b/150927776).
359 _T = TypeVar('_T')
360
361
362 class _DataclassParser(flags.ArgumentParser, Generic[_T]):
363 """Parser for a config defined inline (not from a file)."""
364
365 def __init__(self, name: str, dataclass_type: Type[_T],
366 parse_fn: Optional[Callable[[Any], _T]] = None):
367 self.name = name
368 self.dataclass_type = dataclass_type
369 self.parse_fn = parse_fn
370
371 def _get_parse_fn(self):
372 # NB: We are using lazy lookup in the parse function rather than
373 # constructor, to give client's code a chance to create their parsers
374 # and provide consistency with availability of parsers for nested fields
375 # (which are also looked up during parsing).
376 if self.parse_fn:
377 return self.parse_fn
378 if self.dataclass_type in _FIELD_TYPE_TO_PARSER:
379 return _FIELD_TYPE_TO_PARSER[self.dataclass_type].parse
380
381 def parse(self, config: Any) -> _T:
382 # It is important to use deepcopy here, so if parser returns constants
383 # they are not modified during the flag parsing.
384 if isinstance(config, self.dataclass_type):
385 return copy.deepcopy(config)
386 parse_fn = self._get_parse_fn()
387 if parse_fn:
388 return copy.deepcopy(parse_fn(config))
389 raise TypeError(
390 'Overriding {} is not allowed: it has neither '
391 'registered parser nor explicit parse_fn in the flag '
392 'definition'.format(self.name)
393 )
394
395 def flag_type(self):
396 return 'config_dataclass({})'.format(self.dataclass_type)
397
398
399 def DEFINE_config_dataclass( # pylint: disable=invalid-name
400 name: str,
401 config: _T,
402 help_string: str = 'Configuration object. Must be a dataclass.',
403 flag_values: flags.FlagValues = FLAGS,
404 sys_argv: Optional[List[str]] = None,
405 parse_fn: Optional[Callable[[Any], _T]] = None,
406 **kwargs,
407 ) -> flags.FlagHolder[_T]:
408 """Defines a typed (dataclass) flag-overrideable configuration.
409
410 Similar to `DEFINE_config_dict` except `config` should be a `dataclass`.
411
412 The config value can contain nested fields, including other dataclasses.
413 If a field is of form Optional[dataclass] with None as a default value,
414 it can be explicitly initialized using special value `build`. E.g.
415 For instance:
416
417 ```
418 @dc.dataclass
419 class FancyLoss
420 foo_scale: float = 0.1
421
422 @dc.dataclass
423 class Config:
424 fancy_loss: Optional[FancyLoss] = None
425 ```
426
427 Then if `--config.fancy_loss=build --config.fancy_loss.foo_scale=1` will
428 instantiate and override foo_scale to 1. Note: that the reverse
429 order is not allowed: `--config.fancy_loss.foo_scale=1
430 --config.fancy_loss=build` will cause FlagOrderError.
431
432 Optional dataclass fields can also be set to None using special `none` value.
433 For instance:
434
435 ```
436 @dc.dataclass
437 class FancyLossConfig
438 foo_loss_scale: float = 0.1
439
440 @dc.dataclass
441 class Config:
442 fancy_loss: Optional[FancyLossConfig] = FancyLossConfig()
443 ```
444
445 Then `--config.fancy_loss=none`, will set it to None.
446
447 Implementation note: This flag will register all the needed nested flags
448 dynamically based on sys.argv or sys_argv, in order to support
449 free-text keyed flags such as `foo.bar['i']=1`. Because of how flag subsystem
450 works this will happen either at flag-parsing time (during app.run),
451 if there is a root level override, such as `--config=<..>` or during
452 declaration otherwise (during this invocation).
453 Parsing at declaration (e.g. if no root override) can cause problems
454 with multiprocessing since sys.argv is not yet populated at
455 declaration time for spawn processes. To avoid this, pass custom sys_argv
456 value instead if you want to use this library with multiprocessing.
457 Also note, in the future we might consider to always do it at declaration
458 time, as this cleans up the logic significantly.
459
460 Args:
461 name: Flag name.
462 config: A user-defined configuration object. Must be built via `dataclass`.
463 help_string: Help string to display when --helpfull is called.
464 flag_values: FlagValues instance used for parsing.
465 sys_argv: If set, interprets this as the full list of args used in parsing.
466 This is used to identify which overrides to define as flags. If not
467 specified, uses the system sys.argv to figure it out.
468 parse_fn: Function that can parse provided flag value, when assigned via
469 flag.value, or passed on command line. If not provided, but the class has
470 registered parser register_flag_parser_for_type, the latter will be used.
471 Otherwise only allows to assign instances of this class.
472 **kwargs: Optional keyword arguments passed to Flag constructor.
473
474 Returns:
475 A handle to the defined flag.
476 """
477
478 if not dataclasses.is_dataclass(config):
479 raise ValueError('Configuration object must be a `dataclass`.')
480 # Define the flag.
481 parser = _DataclassParser(name=name, dataclass_type=type(config),
482 parse_fn=parse_fn)
483 flag = _ConfigFlag(
484 flag_values=flag_values,
485 parser=parser,
486 serializer=flags.ArgumentSerializer(),
487 name=name,
488 default=config,
489 help_string=help_string,
490 sys_argv=sys_argv,
491 **kwargs)
492
493 return flags.DEFINE_flag(flag, flag_values)
494
495
496 def get_config_filename(config_flag) -> str: # pylint: disable=g-bad-name
497 """Returns the path to the config file given the config flag.
498
499 Args:
500 config_flag: The flag instance obtained from FLAGS, e.g. FLAGS['config'].
501
502 Returns:
503 the path to the config file.
504 """
505 if not is_config_flag(config_flag):
506 raise TypeError('expect a config flag, found {}'.format(type(config_flag)))
507 return config_flag.config_filename
508
509
510 def get_override_values(config_flag) -> Dict[str, Any]: # pylint: disable=g-bad-name
511 """Returns a flat dict containing overridden values from the config flag.
512
513 Args:
514 config_flag: The flag instance obtained from FLAGS, e.g. FLAGS['config'].
515
516 Returns:
517 a flat dict containing overridden values from the config flag.
518 """
519 if not is_config_flag(config_flag):
520 raise TypeError('expect a config flag, found {}'.format(type(config_flag)))
521 return config_flag.override_values
522
523
524 class _IgnoreFileNotFoundAndCollectErrors:
525 """Helps recording "file not found" exceptions when loading config.
526
527 Usage:
528 ignore_errors = _IgnoreFileNotFoundAndCollectErrors()
529 with ignore_errors.Attempt('Loading from foo', 'bar.id'):
530 ...
531 return True # successfully loaded from `foo`
532 logging.error('Failed loading: {}'.format(ignore_errors.DescribeAttempts()))
533 """
534
535 def __init__(self):
536 self._attempts = [] # type: List[Tuple[Tuple[str, str], IOError]]
537
538 def Attempt(self, description, path):
539 """Creates a context manager that routes exceptions to this class."""
540 self._current_attempt = (description, path)
541 ignore_errors = self
542
543 class _ContextManager:
544
545 def __enter__(self):
546 return self
547
548 def __exit__(self, exc_type, exc_value, unused_traceback):
549 return ignore_errors.ProcessAttemptException(exc_type, exc_value)
550
551 return _ContextManager()
552
553 def ProcessAttemptException(self, exc_type, exc_value):
554 if exc_type is FileNotFoundError and exc_value.errno == errno.ENOENT: # pytype: disable=attribute-error # trace-all-classes
555 self._attempts.append((self._current_attempt, exc_value)) # pytype: disable=container-type-mismatch # trace-all-classes
556 # Returning a true value suppresses exceptions:
557 # https://docs.python.org/2/reference/datamodel.html#object.__exit__
558 return True
559
560 def DescribeAttempts(self):
561 return '\n'.join(
562 ' Attempted [{}]:\n {}\n {}'.format(attempt[0], attempt[1], e)
563 for attempt, e in self._attempts)
564
565
566 def _MakeDefaultOrNone(kls, config, allow_none=True, field_path=''):
567 if config in ['build', True]:
568 try:
569 return kls()
570 except Exception as e:
571 raise ValueError(
572 f'Unable to create default instance for "{field_path}" '
573 f'of type "{kls}": {e}') from e
574
575 elif (config in ['0', 0, False] or config.lower() == 'none'):
576 if not allow_none:
577 raise ValueError(f'None is not allowed as value for "{field_path}", '
578 'as the dataclass field is not marked as optional.')
579 return None
580 raise ValueError(f'Unable to parse value "{config}" as instance of {kls}'
581 f'for {field_path} values allowed are [0/none, or 1]')
582
583
584 def _LoadConfigModule(name: str, path: str):
585 """Loads a script from external file specified by path.
586
587 Unprefixed path is looked for in the current working directory using
588 regular file open operation. This should work with relative config paths.
589
590 Args:
591 name: Name of the new module.
592 path: Path to the .py file containing the module.
593
594 Returns:
595 Module loaded from the given path.
596
597 Raises:
598 IOError: If the config file cannot be found.
599 """
600 if not path:
601 raise IOError('Path to config file is an empty string.')
602
603 ignoring_errors = _IgnoreFileNotFoundAndCollectErrors()
604
605 # Works for relative paths.
606 with ignoring_errors.Attempt('Relative path', path):
607 config_module = _load_source(name, path)
608 return config_module
609
610 # Nothing worked. Log the paths that were attempted.
611 raise IOError('Failed loading config file {}\n{}'.format(
612 name, ignoring_errors.DescribeAttempts()))
613
614
615 class _ErrorConfig:
616 """ConfigDict object that raises an error on any attribute access."""
617
618 def __init__(self, error):
619 super(_ErrorConfig, self).__init__()
620 super(_ErrorConfig, self).__setattr__('_error', error)
621
622 def __getattr__(self, attr):
623 self._ReportError()
624
625 def __setattr__(self, attr, value):
626 self._ReportError()
627
628 def __delattr__(self, attr):
629 self._ReportError()
630
631 def __getitem__(self, key):
632 self._ReportError()
633
634 def __setitem__(self, key, value):
635 self._ReportError()
636
637 def __delitem__(self, key):
638 self._ReportError()
639
640 def _ReportError(self): # pylint: disable=invalid-name
641 raise IOError(
642 'Configuration is not available because of an earlier failure to load:'
643 f' {self._error}'
644 ) from self._error
645
646
647 def _LockConfig(config):
648 """Calls config.lock() if config has a lock method."""
649 if isinstance(config, _ErrorConfig):
650 pass # Attempting to access _ErrorConfig.lock will raise its error.
651 elif getattr(config, 'lock', None) and callable(config.lock):
652 config.lock()
653 else:
654 pass # config.lock() does not have desired semantics, do nothing.
655
656
657 class ConfigFileFlagParser(flags.ArgumentParser):
658 """Parser for config files."""
659
660 def __init__(self, name, lock_config=True):
661 self.name = name
662 self._lock_config = lock_config
663
664 def parse(self, path):
665 """Loads a config module from `path` and returns the `get_config()` result.
666
667 If a colon is present in `path`, everything to the right of the first colon
668 is passed to `get_config` as an argument. This allows the structure of what
669 is returned to be modified, which is useful when performing complex
670 hyperparameter sweeps.
671
672 Args:
673 path: string, path pointing to the config file to execute. May also
674 contain a config_string argument, e.g. be of the form
675 "config.py:some_configuration".
676 Returns:
677 Result of calling `get_config` in the specified module.
678 """
679 # This will be a 2 element list iff extra configuration args are present.
680 split_path = path.split(':', 1)
681 try:
682 config_module = _LoadConfigModule('{}_config'.format(self.name),
683 split_path[0])
684 config = config_module.get_config(*split_path[1:])
685 if config is None:
686 logging.warning(
687 '%s:get_config() returned None, did you forget a return statement?',
688 path)
689 except IOError as e:
690 # Don't raise the error unless/until the config is actually accessed.
691 config = _ErrorConfig(e)
692 # Third party flags library catches TypeError and ValueError and rethrows,
693 # removing useful information unless it is added here (b/63877430):
694 except (TypeError, ValueError) as e:
695 error_trace = traceback.format_exc()
696 raise type(e)('Error whilst parsing config file:\n\n' + error_trace)
697
698 if self._lock_config:
699 _LockConfig(config)
700
701 return config
702
703 def flag_type(self):
704 return 'config object'
705
706
707 # Alias to an older name, for backwards compatibility.
708 _ConfigFileParser = ConfigFileFlagParser
709
710
711 class _InlineConfigParser(flags.ArgumentParser):
712 """Parser for a config defined inline (not from a file)."""
713
714 def __init__(self, name, lock_config=True):
715 self.name = name
716 self._lock_config = lock_config
717
718 def parse(self, config):
719 if not isinstance(config, config_dict.ConfigDict):
720 raise TypeError('Overriding {} is not allowed.'.format(self.name))
721 if self._lock_config:
722 _LockConfig(config)
723 return config
724
725 def flag_type(self):
726 return 'config object'
727
728
729 class _ConfigFlag(flags.Flag):
730 """Flag definition for command-line overridable configs."""
731
732 def __init__(
733 self,
734 flag_values=FLAGS,
735 *,
736 accept_new_attributes: bool = False,
737 sys_argv=None,
738 **kwargs,
739 ):
740 # Parent constructor can already call .Parse, thus additional fields
741 # have to be set here.
742 self.flag_values = flag_values
743 self._accept_new_attributes = accept_new_attributes
744 # Note, we don't replace sys_argv with sys.argv here if it's None because
745 # in some obscure multiprocessing use cases, sys.argv may not be populated
746 # until later and we need to look it up at parse time.
747 self._sys_argv = sys_argv
748 super(_ConfigFlag, self).__init__(**kwargs)
749
750 def _GetArgv(self):
751 """Lazily fetches sys.argv and expands any potential --flagfile=..."""
752 argv = sys.argv if self._sys_argv is None else self._sys_argv
753 argv = flags.FLAGS.read_flags_from_files(argv, force_gnu=False)
754 return argv
755
756 def _GetOverrides(self, argv):
757 """Parses the command line arguments for the overrides."""
758 # We use a dict to keep the order of the overrides.
759 overrides = dict()
760 config_index = self._FindConfigSpecified(argv)
761 for i, arg in enumerate(argv):
762 if re.match(r'-{{1,2}}(no)?{}\.'.format(self.name), arg):
763 if config_index > 0 and i < config_index:
764 raise FlagOrderError('Found {} in argv before a value for --{} '
765 'was specified'.format(arg, self.name))
766 arg_name = arg.split('=', 1)[0]
767 override_name = arg_name.split('.', 1)[1]
768 # Reinsert override_name into overrides to keep the order of
769 # the "last" flag.
770 overrides[override_name] = overrides.pop(override_name, None)
771 return list(overrides)
772
773 def _FindConfigSpecified(self, argv):
774 """Finds element in argv specifying the value of the config flag.
775
776 Args:
777 argv: command line arguments as a list of strings.
778 Returns:
779 Index in argv if found and -1 otherwise.
780 """
781 for i, arg in enumerate(argv):
782 # '-(-)config' followed by '=' or at the end of the string.
783 if re.match(r'^-{{1,2}}{}(=|$)'.format(self.name), arg) is not None:
784 return i
785 return -1
786
787 def _IsConfigSpecified(self, argv):
788 """Returns `True` if the config file is specified on the command line."""
789 return self._FindConfigSpecified(argv) >= 0
790
791 def _set_default(self, default):
792 if self._IsConfigSpecified(self._GetArgv()):
793 self.default = default
794 else:
795 super(_ConfigFlag, self)._set_default(default) # pytype: disable=attribute-error
796 self.default_as_str = "'{}'".format(default)
797
798 def _validate_overrides(self, config, overrides: Sequence[str]):
799 # Verify that we don't provide --config.foo.bar=1 followed by override of
800 # config.foo.
801 for i, override_a in enumerate(overrides, 1):
802 for override_b in overrides[i:]:
803 # verify if override_b will overwrite override_a
804 if override_a.startswith(override_b + '.'):
805 raise FlagOrderError(
806 f'Flag --{self.name}.{override_b} is provided after '
807 f'--{self.name}.{override_a} and '
808 'it will overwrite the value provided in '
809 f'--{self.name}.{override_a}, '
810 'which is probably not what you expect.')
811
812 def _initialize_missing_parent_fields(self, config, overrides):
813 for override in overrides:
814 config_path.initialize_missing_parent_fields(
815 config, override, overrides)
816
817 def _parse(self, argument):
818 # Parse config
819 config = super(_ConfigFlag, self)._parse(argument)
820
821 # Get list or overrides
822 overrides = self._GetOverrides(self._GetArgv())
823 # Iterate over overridden fields and create valid parsers
824 self._override_values = {}
825 self._initialize_missing_parent_fields(config, overrides)
826 self._validate_overrides(config, overrides)
827
828 if self._accept_new_attributes:
829 # If user provide a new attribute, fallback to `object` to accept all
830 # literal
831 default_type = object
832 else:
833 default_type = None
834
835 for field_path in overrides:
836 field_type = config_path.get_type(
837 field_path, config, default_type=default_type
838 )
839 field_type_origin = config_path.get_origin(field_type)
840 field_help = 'An override of {}\'s field {}'.format(self.name, field_path)
841 field_name = '{}.{}'.format(self.name, field_path)
842
843 parser = None
844 if field_type in _FIELD_TYPE_TO_PARSER:
845 parser = _FIELD_TYPE_TO_PARSER[field_type]
846 elif isinstance(field_type, type) and issubclass(
847 field_type, config_dict.ConfigDict
848 ):
849 # Supports ConfigDict sub-classes.
850 parser = _FIELD_TYPE_TO_PARSER[config_dict.ConfigDict]
851 elif field_type_origin and field_type_origin in _FIELD_TYPE_TO_PARSER:
852 parser = _FIELD_TYPE_TO_PARSER[field_type_origin]
853 elif issubclass(field_type, enum.Enum):
854 parser = flags.EnumClassParser(field_type, case_sensitive=False)
855 elif dataclasses.is_dataclass(field_type):
856 # For dataclasses-valued fields allow default instance creation.
857 is_optional = config_path.is_optional(field_path, config)
858 parser = _DataclassParser(
859 name=field_path, dataclass_type=field_type,
860 parse_fn=ft.partial(_MakeDefaultOrNone, field_type,
861 allow_none=is_optional, field_path=field_path))
862
863 if parser:
864 if not isinstance(parser, tuple_parser.TupleParser):
865 if isinstance(parser, (_LiteralParser, _ConfigDictParser)):
866 # We do not pass the default to `_ConfigFieldFlag`, otherwise
867 # `_LiteralParser.parse(default)` is called with `default`,
868 # which would try to parse string.
869 # Setting the value to `None` never call `.parse`, so the
870 # default value from the config is kept.
871 # TODO(sandler): Investigate if value could be None for all parsers.
872 default = None
873 else:
874 default = config_path.get_value(field_path, config)
875 flag = _ConfigFieldFlag(
876 path=field_path,
877 config=config,
878 override_values=self._override_values,
879 parser=parser,
880 serializer=flags.ArgumentSerializer(),
881 name=field_name,
882 default=default,
883 accept_new_attributes=self._accept_new_attributes,
884 help_string=field_help,
885 )
886 # Literal values support the `--my_bool` / `--nomy_bool` syntax
887 flag.boolean = field_type is bool or isinstance(
888 parser, _LiteralParser
889 )
890 flags.DEFINE_flag(flag=flag, flag_values=self.flag_values)
891 elif field_name not in self.flag_values:
892 # Overriding a tuple field. Define the flag only once -- it might
893 # appear multiple times on the command-line (e.g.
894 # `--config.flag a --config.flag b`) but defining the same flag
895 # multiple times is an error. All arguments for the same flag are
896 # passed to a single call of _ConfigFieldMultiFlag.parse.
897 flag = _ConfigFieldMultiFlag(
898 path=field_path,
899 config=config,
900 override_values=self._override_values,
901 parser=parser,
902 serializer=flags.ArgumentSerializer(),
903 name=field_name,
904 default=config_path.get_value(field_path, config),
905 help_string=field_help,
906 )
907 flags.DEFINE_flag(flag=flag, flag_values=self.flag_values)
908 else:
909 raise UnsupportedOperationError(
910 "Type {} of field {} is not supported for overriding. "
911 "Currently supported types are: {}. (Note that tuples should "
912 "be passed as a string on the command line, `--flag='(a, b, c)'`, "
913 "or by repeated flags, `--flag=1 --flag=2 --flag=3`, rather than "
914 "--flag=(a, b, c).)".format(
915 field_type, field_name, _FIELD_TYPE_TO_PARSER.keys()))
916
917 self._config_filename = argument
918 return config
919
920 def serialize(self):
921 # Use the config filename instead of the dictionary when serializing.
922 return self._serialize(self.config_filename)
923
924 @property
925 def config_filename(self):
926 """Returns a path to a config file.
927
928 Typical usage example:
929 `script.py`:
930
931 ```python
932 ...
933 from absl import flags
934 from ml_collections import config_flags
935
936 FLAGS = flags.FLAGS
937 _CONFIG = config_flags.DEFINE_config_file(
938 name='my_config',
939 default='ml_collections/config_flags/tests/configdict_config.py',
940 help_string='config file')
941 ...
942
943 FLAGS['my_config'].config_filename
944
945 will output
946 'ml_collections/config_flags/tests/configdict_config.py'
947 ```
948
949 Returns:
950 A path to a config file. For a parameterised get_config, the config
951 filename with the provided parameterisation is returned.
952
953 Raises:
954 UnparsedFlagError: if the flag has not been parsed.
955
956 """
957 if not hasattr(self, '_config_filename'):
958 raise UnparsedFlagError('The flag has not been parsed yet')
959 return self._config_filename
960
961 @property
962 def override_values(self):
963 """Returns a flat dictionary containing overridden values.
964
965 Keys in the dictionary are dot-separated paths navigating to child items in
966 the original configuration. For example, supppose that a `config` flag is
967 defined and initialized to the following configuration:
968
969 ```python
970 {
971 'a': 1,
972 'nested': {
973 'b': 2
974 }
975 }
976 ```
977
978 and the user overrides both values using command-line flags:
979
980 ```
981 --config.a=10 --config.nested.b=20
982 ```
983
984 Then `FLAGS['config'].override_values` will return:
985
986 ```python
987 {
988 'a': 10,
989 'nested.b': 20
990 }
991 ```
992
993 The result can be passed to `ConfigDict.update_from_flattened_dict` to
994 update the values in a configuration. Continuing with the example above:
995
996 ```python
997 from ml_collections import config_dict
998 config = config_dict.ConfigDict{
999 'a': 123,
1000 'nested': {
1001 'b': 456
1002 }
1003 }
1004 config.update_from_flattened_dict(FLAGS['config'].override_values)
1005 print(config.a) # Prints `10`.
1006 print(config.nested.b) # Prints `20`.
1007 ```
1008
1009 Returns:
1010 Flat dictionary with overridden values.
1011
1012 Raises:
1013 UnparsedFlagError: if the flag has not been parsed.
1014 """
1015 if not hasattr(self, '_override_values'):
1016 raise UnparsedFlagError('The flag has not been parsed yet')
1017 return self._override_values
1018
1019
1020 def is_config_flag(flag): # pylint: disable=g-bad-name
1021 """Returns True iff `flag` is an instance of `_ConfigFlag`.
1022
1023 External users of the library may need to check if a flag is of this type
1024 or not, particularly because ConfigFlags should be parsed before any other
1025 flags. This function allows that test to be done without making the whole
1026 class public.
1027
1028 Args:
1029 flag: Flag object.
1030
1031 Returns:
1032 True iff `isinstance(flag, _ConfigFlag)` is true.
1033 """
1034 return isinstance(flag, _ConfigFlag)
1035
1036
1037 class _ConfigFieldFlag(flags.Flag):
1038 """Flag for updating a field in a ConfigDict."""
1039
1040 def __init__(
1041 self,
1042 path: str,
1043 config: config_dict.ConfigDict,
1044 override_values: MutableMapping[str, Any],
1045 *,
1046 parser: flags.ArgumentParser,
1047 serializer: flags.ArgumentSerializer,
1048 name: str,
1049 default: Any,
1050 help_string: str,
1051 short_name: Optional[str] = None,
1052 boolean: bool = False,
1053 accept_new_attributes: bool = False,
1054 ):
1055 """Creates new flag with callback."""
1056 super().__init__(
1057 parser=parser,
1058 serializer=serializer,
1059 name=name,
1060 default=default,
1061 help_string=help_string,
1062 short_name=short_name,
1063 boolean=boolean)
1064 self._path = path
1065 self._config = config
1066 self._override_values = override_values
1067 self._accept_new_attributes = accept_new_attributes
1068
1069 def parse(self, argument):
1070 super().parse(argument)
1071 # Callback to set value in ConfigDict.
1072 config_path.set_value(
1073 self._path, self._config, self.value,
1074 accept_new_attributes=self._accept_new_attributes,
1075 )
1076 self._override_values[self._path] = self.value
1077
1078
1079 class _ConfigFieldMultiFlag(flags.MultiFlag):
1080 """Flag for updating a tuple field in a ConfigDict."""
1081
1082 def __init__(
1083 self,
1084 path: str,
1085 config: config_dict.ConfigDict,
1086 override_values: MutableMapping[str, Any],
1087 *,
1088 parser: flags.ArgumentParser,
1089 serializer: flags.ArgumentSerializer,
1090 name: str,
1091 default: Any,
1092 help_string: str,
1093 short_name: Optional[str] = None,
1094 boolean: bool = False,
1095 ):
1096 """Creates new flag with callback."""
1097 super().__init__(
1098 parser=parser,
1099 serializer=serializer,
1100 name=name,
1101 default=default,
1102 help_string=help_string,
1103 short_name=short_name,
1104 boolean=boolean)
1105 self._path = path
1106 self._config = config
1107 self._override_values = override_values
1108
1109 def parse(self, arguments):
1110 super().parse(arguments)
1111 # Callback to set value in ConfigDict.
1112 config_path.set_value(self._path, self._config, tuple(self.value))
1113 self._override_values[self._path] = tuple(self.value)
1114
1115 def _parse(self, arguments):
1116 # MultiFlag passes each argument one-at-a-time to the parser.parse. Just
1117 # call Flag._parse (grandparent class) directly so all arguments are passed
1118 # to parser.parse in a single call.
1119 result = flags.Flag._parse(self, arguments) # pylint: disable=protected-access
1120 return list(result)
1121
1122
1123 def register_flag_parser_for_type(
1124 field_type: _T, parser: flags.ArgumentParser) -> _T:
1125 """Registers parser for a given type.
1126
1127 See documentation for `register_flag_parser` for usage example.
1128
1129 Args:
1130 field_type: field type to register
1131 parser: parser to use
1132
1133 Returns:
1134 field_type unmodified.
1135 """
1136 _FIELD_TYPE_TO_PARSER[field_type] = parser
1137 return field_type
1138
1139
1140 def register_flag_parser(*, parser: flags.ArgumentParser) -> Callable[[_T], _T]:
1141 """Creates a decorator to register parser on types.
1142
1143 For example:
1144
1145 ```
1146 class ParserForCustomConfig(flags.ArgumentParser):
1147 def parse(self, value):
1148 if isinstance(value, CustomConfig):
1149 return value
1150 return CustomConfig(i=int(value), j=int(value))
1151
1152
1153 @config_flags.register_flag_parser(parser=ParserForCustomConfig())
1154 @dataclasses.dataclass
1155 class CustomConfig:
1156 i: int = None
1157 j: int = None
1158
1159 class MainConfig:
1160 sub: CustomConfig = CustomConfig()
1161
1162 config_flags.DEFINE_config_dataclass(
1163 'cfg', MainConfig(), 'MyConfig data')
1164 ```
1165
1166 will declare cfg flag, then passing `--cfg.sub=1`, will initialize
1167 both i and j fields to 1. The fields can still be set individually:
1168 `--cfg.sub=1 --cfg.sub.j=3` will set `i` to `1` and `j` to `3`.
1169
1170 Args:
1171 parser: parser to use.
1172
1173 Returns:
1174 Decorator to apply to types.
1175 """
1176 return ft.partial(register_flag_parser_for_type, parser=parser)