Skip to content

parameters

parameters

Abstract base class for parameter collections with serialization helpers.

Parameters is the common superclass for every configuration group in config/ (DataParameters, TrainingHyperparams, GenerateParameters, etc.). It extends pydantic.BaseModel with:

  • Recursive iteration over nested parameter groups.
  • Name-based lookup across the full parameter tree (get(), has()).
  • YAML / JSON round-trip serialization (from_yaml(), to_yaml(), from_json()).

Classes:

Name Description
Parameters

Abstract base for parameter collections used throughout the config layer.

Parameters pydantic-model

Bases: BaseModel

Abstract base for parameter collections used throughout the config layer.

Subclasses define typed fields (e.g. int, Literal["auto"] | float) and inherit recursive iteration, name-based lookup, and YAML / JSON serialization from this class.

Config:

  • default: pydantic_model_config

explicit_patch()

Compile this model's recursively explicit fields as a sparse patch.

Explicit fields inside nested default models are included even when the parent field itself was never assigned. Patch values are deep-copied by the compiler, so later mutations cannot affect patch application.

Source code in src/nemo_safe_synthesizer/configurator/parameters.py
def explicit_patch(self) -> CompiledConfigPatch[Self]:
    """Compile this model's recursively explicit fields as a sparse patch.

    Explicit fields inside nested default models are included even when the
    parent field itself was never assigned. Patch values are deep-copied by
    the compiler, so later mutations cannot affect patch application.
    """
    model_type = type(self)
    return CompiledConfigPatch.from_model(model_type, self, origin="typed config", precedence=0)

apply_patch(patch)

Overlay a compiled patch on this full model and validate once.

The base is materialized in full so environment-backed and validator- resolved defaults keep their current values. Patch assignments retain their relative precedence and always follow the base.

Source code in src/nemo_safe_synthesizer/configurator/parameters.py
def apply_patch(self, patch: CompiledConfigPatch[Self]) -> Self:
    """Overlay a compiled patch on this full model and validate once.

    The base is materialized in full so environment-backed and validator-
    resolved defaults keep their current values. Patch assignments retain
    their relative precedence and always follow the base.
    """
    return patch.apply_to_full_model(self)

from_config_source(source=None, *, unknown_field_behavior='ignore', **kwargs) classmethod

Normalize one sparse config source plus higher-precedence keyword values.

source may be None, an instance of exactly cls, or a raw mapping. Declared compatibility aliases are normalized for raw mappings and keyword overrides. unknown_field_behavior controls whether unknown raw mapping keys are ignored or rejected. Keyword overrides accept top-level fields and canonical dotted paths, but reject inferred bare nested names with an actionable path suggestion. A different Pydantic model type is rejected rather than adapted.

Source code in src/nemo_safe_synthesizer/configurator/parameters.py
@classmethod
def from_config_source(
    cls,
    source: Self | Mapping[str, object] | None = None,
    *,
    unknown_field_behavior: UnknownFieldBehavior = "ignore",
    **kwargs: object,
) -> Self:
    """Normalize one sparse config source plus higher-precedence keyword values.

    ``source`` may be ``None``, an instance of exactly ``cls``, or a raw
    mapping. Declared compatibility aliases are normalized for raw mappings
    and keyword overrides. ``unknown_field_behavior`` controls whether
    unknown raw mapping keys are ignored or rejected. Keyword overrides
    accept top-level fields and canonical dotted paths, but reject inferred
    bare nested names with an actionable path suggestion. A different
    Pydantic model type is rejected rather than adapted.
    """
    schema = ParameterSchema.from_model(cls)
    match source:
        case None:
            source_patch = CompiledConfigPatch.from_mapping(
                cls, {}, origin="empty config", precedence=0, unknown_fields="reject"
            )
        case BaseModel() as model:
            if type(model) is not cls:
                raise TypeError(f"Expected {cls.__name__}, got {type(model).__name__}")
            source_patch = CompiledConfigPatch.from_model(
                cls,
                cast(Self, model),
                origin="typed config",
                precedence=0,
            )
        case Mapping() as mapping:
            source_patch = CompiledConfigPatch.from_mapping(
                cls,
                schema.normalize_aliases(cast(Mapping[str, object], mapping)),
                origin="mapping config",
                precedence=0,
                unknown_fields=unknown_field_behavior,
            )
        case _:
            raise TypeError(f"Unsupported config type: {type(source)}")

    overrides = CompiledConfigPatch.from_paths(
        cls,
        (
            PatchAssignment(schema.require(name, infer_bare_name=False), value, f"keyword override {name!r}", 1)
            for name, value in kwargs.items()
        ),
    )
    return source_patch.combine(overrides).apply()

get(name, default=None)

Look up a parameter or sub-group by name across the full tree.

Explicit dotted paths such as "generation.validation.foo" resolve directly. Bare names are accepted only when they map to exactly one field in the parameter tree.

Parameters:

Name Type Description Default
name str

Field name to search for.

required
default Any

Value returned when name is not found.

None

Returns:

Type Description
DataT | Any | None

The parameter value or sub-group if found, otherwise default.

Source code in src/nemo_safe_synthesizer/configurator/parameters.py
def get(self, name: str, default: Any = None) -> DataT | Any | None:
    """Look up a parameter or sub-group by name across the full tree.

    Explicit dotted paths such as ``"generation.validation.foo"`` resolve
    directly. Bare names are accepted only when they map to exactly one
    field in the parameter tree.

    Args:
        name: Field name to search for.
        default: Value returned when ``name`` is not found.

    Returns:
        The parameter value or sub-group if found, otherwise ``default``.
    """
    if PARAMETER_PATH_SEPARATOR in name:
        value = self._get_field_path(tuple(name.split(PARAMETER_PATH_SEPARATOR)))
        return default if value is _MISSING else value

    matches = self._matching_field_paths(name)
    if not matches:
        return default
    _, value = matches[0]
    return value

has(name)

Check whether name exists anywhere in the parameter tree.

Unlike get(), this does not conflate falsy values (0, "", False, None) with absence. Bare names are accepted only when they map to at most one field in the parameter tree.

Parameters:

Name Type Description Default
name str

Field name to search for.

required

Returns:

Type Description
bool

True if the parameter or sub-group exists.

Source code in src/nemo_safe_synthesizer/configurator/parameters.py
def has(self, name: str) -> bool:
    """Check whether ``name`` exists anywhere in the parameter tree.

    Unlike ``get()``, this does not conflate falsy values (``0``, ``""``,
    ``False``, ``None``) with absence. Bare names are accepted only when
    they map to at most one field in the parameter tree.

    Args:
        name: Field name to search for.

    Returns:
        ``True`` if the parameter or sub-group exists.
    """
    if PARAMETER_PATH_SEPARATOR in name:
        return self._get_field_path(tuple(name.split(PARAMETER_PATH_SEPARATOR))) is not _MISSING
    return bool(self._matching_field_paths(name))

from_yaml_str(raw) classmethod

Construct an instance from a YAML-formatted string.

Parameters:

Name Type Description Default
raw str

YAML content as a string.

required

Returns:

Type Description
Self

A validated Parameters instance.

Source code in src/nemo_safe_synthesizer/configurator/parameters.py
@classmethod
def from_yaml_str(cls, raw: str) -> Self:
    """Construct an instance from a YAML-formatted string.

    Args:
        raw: YAML content as a string.

    Returns:
        A validated ``Parameters`` instance.
    """
    data = yaml.safe_load(raw)
    return cls.model_validate(data)

from_json(path, overrides=None) classmethod

Load from a JSON file, optionally applying field overrides.

Parameters:

Name Type Description Default
path PathT

Path to the JSON file.

required
overrides dict | None

Field-level overrides applied via model_copy(update=...).

None

Returns:

Type Description
Self

A validated Parameters instance.

Source code in src/nemo_safe_synthesizer/configurator/parameters.py
@classmethod
def from_json(cls, path: PathT, overrides: dict | None = None) -> Self:
    """Load from a JSON file, optionally applying field overrides.

    Args:
        path: Path to the JSON file.
        overrides: Field-level overrides applied via ``model_copy(update=...)``.

    Returns:
        A validated ``Parameters`` instance.
    """
    with open(path, "r") as f:
        data = json.load(f)
    params = cls.model_validate(data)
    if overrides:
        params = params.model_copy(update=overrides)
    return params

from_yaml(path, overrides=None) classmethod

Load from a YAML file, optionally applying field overrides.

Parameters:

Name Type Description Default
path PathT

Path to the YAML file.

required
overrides dict | None

Field-level overrides applied via model_copy(update=...).

None

Returns:

Type Description
Self

A validated Parameters instance.

Raises:

Type Description
FileNotFoundError

If path does not exist.

Source code in src/nemo_safe_synthesizer/configurator/parameters.py
@classmethod
def from_yaml(cls, path: PathT, overrides: dict | None = None) -> Self:
    """Load from a YAML file, optionally applying field overrides.

    Args:
        path: Path to the YAML file.
        overrides: Field-level overrides applied via ``model_copy(update=...)``.

    Returns:
        A validated ``Parameters`` instance.

    Raises:
        FileNotFoundError: If ``path`` does not exist.
    """
    pth = Path(path)
    if not pth.exists():
        raise FileNotFoundError(f"File {pth} does not exist")
    with pth.open("r") as f:
        data = yaml.safe_load(f)
    params = cls.model_validate(data)
    if overrides:
        params = params.model_copy(update=overrides)
    return params

to_yaml(path, exclude_unset=True)

Serialize this instance to a YAML file.

Parameters:

Name Type Description Default
path PathT

Destination file path.

required
exclude_unset bool

If True, omit fields that were never explicitly set.

True
Source code in src/nemo_safe_synthesizer/configurator/parameters.py
def to_yaml(self, path: PathT, exclude_unset: bool = True) -> None:
    """Serialize this instance to a YAML file.

    Args:
        path: Destination file path.
        exclude_unset: If ``True``, omit fields that were never explicitly set.
    """
    with open(path, "w") as f:
        j = json.loads(self.model_dump_json(exclude_unset=exclude_unset))
        yaml.safe_dump(j, f)

from_params(**kwargs) classmethod

Construct a Parameters instance from keyword arguments.

Parameters:

Name Type Description Default
**kwargs object

Parameter values passed to model_validate.

{}

Returns:

Type Description
Self

A validated Parameters instance.

Source code in src/nemo_safe_synthesizer/configurator/parameters.py
@classmethod
def from_params(cls, **kwargs: object) -> Self:
    """Construct a ``Parameters`` instance from keyword arguments.

    Args:
        **kwargs: Parameter values passed to ``model_validate``.

    Returns:
        A validated ``Parameters`` instance.
    """
    return cls.model_validate(kwargs)

get_auto_params()

Yield field names whose current value is the "auto" sentinel.

Source code in src/nemo_safe_synthesizer/configurator/parameters.py
def get_auto_params(self) -> Iterator[str]:
    """Yield field names whose current value is the ``"auto"`` sentinel."""
    for param in self:
        for field_name, value in param.items():
            if value == "auto":
                yield field_name