bridge.training.utils.omegaconf_utils#
Utilities for working with OmegaConf and dataclass configurations.
Module Contents#
Functions#
Create OmegaConf while tracking excluded fields for later restoration. |
|
Apply overrides while preserving excluded callable fields. |
|
Process a configuration object with optional YAML file and CLI overrides. |
|
Parse and apply Hydra overrides to an OmegaConf config. |
|
Return the |
|
Move flat keys of builder-backed model sections to where the config declares them. |
|
Spell a flat override of a builder-backed model where the config declares the field. |
|
Check if a value is a Hugging Face |
|
Check if a value is a callable that OmegaConf cannot handle. |
|
Recursively convert a dataclass instance to a dictionary suitable for OmegaConf.create. |
|
Track all excluded callable fields and their original values. |
|
Restore excluded callable fields to their original values. |
|
Recursively verify that no callable objects remain in the converted structure. |
|
Recursively apply overrides from a Python dictionary to a dataclass instance. |
Data#
API#
- bridge.training.utils.omegaconf_utils.logger#
‘getLogger(…)’
- bridge.training.utils.omegaconf_utils.DataclassInstance#
‘TypeVar(…)’
- bridge.training.utils.omegaconf_utils._EXCLUDE_FIELD#
‘object(…)’
- bridge.training.utils.omegaconf_utils._SERIALIZABLE_CALLABLE_FIELDS: frozenset[str]#
‘frozenset(…)’
- bridge.training.utils.omegaconf_utils._TRANSFORMER_KEY#
‘transformer’
- bridge.training.utils.omegaconf_utils._METADATA_KEY#
‘extra_checkpoint_metadata’
- bridge.training.utils.omegaconf_utils._METADATA_FIELDS#
‘frozenset(…)’
- bridge.training.utils.omegaconf_utils.create_omegaconf_dict_config(
- config_container: Any,
Create OmegaConf while tracking excluded fields for later restoration.
This function combines the conversion to OmegaConf with tracking of excluded callable fields, allowing them to be restored after override processing.
- Parameters:
config_container – The dataclass instance to convert
- Returns:
Tuple of (OmegaConf DictConfig, excluded fields dictionary)
- Raises:
ValueError – If the conversion fails
- bridge.training.utils.omegaconf_utils.apply_overrides(
- config_obj: bridge.training.utils.omegaconf_utils.DataclassInstance,
- overrides_dict: Dict[str, Any],
- excluded_fields: Dict[str, Any],
Apply overrides while preserving excluded callable fields.
This function first applies the overrides using the standard recursive approach, then restores the callable fields that were excluded during OmegaConf conversion.
- Parameters:
config_obj – The dataclass instance to modify
overrides_dict – Dictionary of override values to apply
excluded_fields – Dictionary of excluded callable fields to restore
- bridge.training.utils.omegaconf_utils.process_config_with_overrides(
- config: bridge.training.utils.omegaconf_utils.DataclassInstance,
- config_filepath: str | None = None,
- cli_overrides: list[str] | None = None,
Process a configuration object with optional YAML file and CLI overrides.
This function provides a unified way to:
Convert the config to OmegaConf while preserving callable fields
Merge an optional YAML configuration file
Apply optional CLI overrides using Hydra syntax
Apply the final configuration back to the original object
Builder-backed model configs keep transformer settings in a nested
transformerfield. A flat key for one of those settings, such asmodel.tensor_model_parallel_size, is routed tomodel.transformer.tensor_model_parallel_sizein the YAML file and in CLI overrides; fields the model config declares itself stay outer. The provider fieldshf_model_idandhf_model_revisionare routed tomodel.extra_checkpoint_metadata, where builder-backed configs record them. CLI overrides apply after the YAML file and in order, so the last one wins whichever spelling it uses. Within the YAML file, a flat key wins over its nested spelling.- Parameters:
config – The dataclass configuration instance to process
config_filepath – Optional path to a YAML config file to merge
cli_overrides – Optional list of Hydra-style CLI override strings
- Returns:
The modified configuration object with all overrides applied
- Raises:
FileNotFoundError – If the specified config_filepath does not exist
OverridesError – If there’s an error parsing CLI overrides
.. rubric:: Example
config = load_recipe(“llama3_8b”) config = process_config_with_overrides( … config, … config_filepath=”my_config.yaml”, … cli_overrides=[“model_config.hidden_size=4096”, “training_config.lr=1e-4”] … )
- bridge.training.utils.omegaconf_utils.parse_hydra_overrides(
- cfg: omegaconf.DictConfig,
- overrides: List[str],
Parse and apply Hydra overrides to an OmegaConf config.
This function uses Hydra’s override parser to support advanced override syntax including additions (+), deletions (~), and complex nested operations.
A flat override of a builder-backed model’s transformer setting or HF source is routed to where that config declares it, as are flat keys that a merged YAML file left in
cfg. See :func:process_config_with_overridesfor the routing and precedence rules.- Parameters:
cfg – OmegaConf config to apply overrides to
overrides – List of Hydra override strings
- Returns:
Updated config with overrides applied
- Raises:
OverridesError – If there’s an error parsing or applying overrides
- exception bridge.training.utils.omegaconf_utils.OverridesError#
Bases:
ExceptionCustom exception for Hydra override parsing errors.
Initialization
Initialize self. See help(type(self)) for accurate signature.
- bridge.training.utils.omegaconf_utils._nested_transformer(
- cfg: omegaconf.DictConfig,
- section_name: str,
Return the
transformermapping of a builder-backed model section, orNone.
- bridge.training.utils.omegaconf_utils._nest_flat_builder_fields(cfg: omegaconf.DictConfig) None#
Move flat keys of builder-backed model sections to where the config declares them.
A key present at both levels is a flat override, for example from a merged YAML file. The flat value wins. Mirrored builder fields are synchronized back to the outer config when overrides are applied. Provider HF source fields belong in checkpoint metadata.
- bridge.training.utils.omegaconf_utils._route_flat_builder_override(
- cfg: omegaconf.DictConfig,
- override: str,
Spell a flat override of a builder-backed model where the config declares the field.
For a builder-backed
model,model.tensor_model_parallel_size=2becomesmodel.transformer.tensor_model_parallel_size=2, keeping any+,++or~prefix, andmodel.hf_model_id=org/namebecomes++model.extra_checkpoint_metadata.hf_model_id=org/name. Other overrides are returned unchanged.
- bridge.training.utils.omegaconf_utils._is_hf_config(val: Any) bool#
Check if a value is a Hugging Face
PretrainedConfigorGenerationConfig.The OmegaConf conversion stores these as
_target_dicts that override application instantiates again, so they are leaves rather than dataclasses to walk field by field. Walking their fields would also fail for heterogeneous configs (Transformers 5.20+), whose per-layer attributes raise when read for the whole model.- Parameters:
val – The value to check
- Returns:
True if the value is a Hugging Face config, False otherwise (or without transformers)
- bridge.training.utils.omegaconf_utils._is_omegaconf_problematic(val: Any) bool#
Check if a value is a callable that OmegaConf cannot handle.
OmegaConf cannot serialize function objects, methods, or partial functions. This function identifies such problematic callables while allowing class types.
- Parameters:
val – The value to check
- Returns:
True if the value is a problematic callable, False otherwise
- bridge.training.utils.omegaconf_utils._dataclass_to_omegaconf_dict(
- val_to_convert: Any,
- path: str = '',
Recursively convert a dataclass instance to a dictionary suitable for OmegaConf.create.
This function completely excludes problematic callable objects to prevent OmegaConf errors. It handles dataclasses, lists, tuples, dictionaries, and primitive types, while converting torch.dtype objects to strings for serialization.
- Parameters:
val_to_convert – The value to convert
path – Current path for debugging (e.g., “model_config.activation_func”)
- Returns:
Converted value suitable for OmegaConf, or _EXCLUDE_FIELD for excluded callables
- bridge.training.utils.omegaconf_utils._track_excluded_fields(
- obj: Any,
- path: str = '',
Track all excluded callable fields and their original values.
This function recursively traverses a dataclass structure and builds a mapping of field paths to their original callable values that will be excluded during OmegaConf conversion.
- Parameters:
obj – The object to analyze for callable fields
path – Current path prefix for building field paths
- Returns:
Dictionary mapping field paths to their original callable values
- bridge.training.utils.omegaconf_utils._restore_excluded_fields(
- config_obj: Any,
- excluded_fields: Dict[str, Any],
Restore excluded callable fields to their original values.
After applying overrides from OmegaConf, this function restores the callable fields that were excluded during the conversion process.
- Parameters:
config_obj – The configuration object to restore fields on
excluded_fields – Dictionary mapping field paths to their original values
- bridge.training.utils.omegaconf_utils._verify_no_callables(obj: Any, path: str = '') bool#
Recursively verify that no callable objects remain in the converted structure.
This function is used for validation to ensure that all problematic callables have been successfully excluded from a data structure before OmegaConf conversion.
- Parameters:
obj – The object to verify
path – Current path for error reporting
- Returns:
True if no problematic callables are found, False otherwise
- bridge.training.utils.omegaconf_utils._apply_overrides(
- config_obj: bridge.training.utils.omegaconf_utils.DataclassInstance,
- overrides_dict: Dict[str, Any],
Recursively apply overrides from a Python dictionary to a dataclass instance.
This function traverses nested dataclass structures and applies override values from a dictionary. It handles type conversions for special cases like torch.dtype. It also handles dictionaries with target fields by instantiating them properly.
- Parameters:
config_obj – The dataclass instance to modify
overrides_dict – Dictionary of override values to apply