bridge.training.utils.omegaconf_utils#

Utilities for working with OmegaConf and dataclass configurations.

Module Contents#

Functions#

create_omegaconf_dict_config

Create OmegaConf while tracking excluded fields for later restoration.

apply_overrides

Apply overrides while preserving excluded callable fields.

process_config_with_overrides

Process a configuration object with optional YAML file and CLI overrides.

parse_hydra_overrides

Parse and apply Hydra overrides to an OmegaConf config.

_nested_transformer

Return the transformer mapping of a builder-backed model section, or None.

_nest_flat_builder_fields

Move flat keys of builder-backed model sections to where the config declares them.

_route_flat_builder_override

Spell a flat override of a builder-backed model where the config declares the field.

_is_hf_config

Check if a value is a Hugging Face PretrainedConfig or GenerationConfig.

_is_omegaconf_problematic

Check if a value is a callable that OmegaConf cannot handle.

_dataclass_to_omegaconf_dict

Recursively convert a dataclass instance to a dictionary suitable for OmegaConf.create.

_track_excluded_fields

Track all excluded callable fields and their original values.

_restore_excluded_fields

Restore excluded callable fields to their original values.

_verify_no_callables

Recursively verify that no callable objects remain in the converted structure.

_apply_overrides

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,
) → Tuple[omegaconf.DictConfig, Dict[str, 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],
) → None#

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,
) → bridge.training.utils.omegaconf_utils.DataclassInstance#

Process a configuration object with optional YAML file and CLI overrides.

This function provides a unified way to:

  1. Convert the config to OmegaConf while preserving callable fields

  2. Merge an optional YAML configuration file

  3. Apply optional CLI overrides using Hydra syntax

  4. Apply the final configuration back to the original object

Builder-backed model configs keep transformer settings in a nested transformer field. A flat key for one of those settings, such as model.tensor_model_parallel_size, is routed to model.transformer.tensor_model_parallel_size in the YAML file and in CLI overrides; fields the model config declares itself stay outer. The provider fields hf_model_id and hf_model_revision are routed to model.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],
) → omegaconf.DictConfig#

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_overrides for 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: Exception

Custom 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,
) → omegaconf.DictConfig | None#

Return the transformer mapping of a builder-backed model section, or None.

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,
) → 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=2 becomes model.transformer.tensor_model_parallel_size=2, keeping any +, ++ or ~ prefix, and model.hf_model_id=org/name becomes ++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 PretrainedConfig or GenerationConfig.

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 = '',
) → Any#

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 = '',
) → Dict[str, Any]#

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],
) → None#

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],
) → None#

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