Source code for kempnerforge.config.loader

"""Config loading: TOML files โ†’ dataclass configs with CLI overrides.

Loading pipeline:
  1. Start from the dataclass field defaults
  2. Import the modules listed in the `plugins` key (registry side effects)
  3. Load TOML file (if provided) and lay the CLI overrides (--model.dim=512 style) over it
  4. Build the config once from the field defaults and the merged layers, so each check,
     and each default that __post_init__ derives from other fields, reads them together
  5. Return JobConfig instance (call .validate(world_size) at distributed setup time)
"""

from __future__ import annotations

import ast
import importlib
import itertools
import shlex
import sys
import tomllib
import types
from dataclasses import fields, is_dataclass
from enum import Enum
from pathlib import Path
from typing import Any, Literal, Union, get_args, get_origin, get_type_hints

from kempnerforge.config.model import CORE_MLP_KEY_ACTIVATIONS, Activation, NormType
from kempnerforge.config.registry import registry
from kempnerforge.config.scheduler import SchedulerType
from kempnerforge.config.schema import JobConfig
from kempnerforge.config.vlm import VLMConfig

_REGISTRY_ENUMS: dict[type[Enum], str] = {
    SchedulerType: "scheduler",
    NormType: "norm",
    Activation: "mlp",
}


def _coerce_registry_enum(enum_type: type[Enum], category: str, value: Any) -> Any:
    """Coerce ``value`` to an ``enum_type`` member, or keep a name ``category`` registers.

    These enums select a registry builder, so a name a plugin registered is valid
    though the enum does not list it, and it stays a plain ``str``. ``Activation``
    reads ``mlp``: ``build_mlp`` maps the built-in activations to ``mlp`` keys and
    looks any other name up there directly. Core's own ``mlp`` keys pass through
    whatever was imported, so ``ModelConfig`` rejects each with the activation
    that selects it, and they are left out of the names the error lists.

    Raises:
        ValueError: ``value`` is neither a member nor a registered name; the
            message lists both.
    """
    try:
        return enum_type(value)
    except ValueError:
        core_keys = frozenset(CORE_MLP_KEY_ACTIVATIONS) if enum_type is Activation else frozenset()
        if isinstance(value, str) and value in core_keys:
            return value
        registered = [name for name in registry.list(category) if name not in core_keys]
        if isinstance(value, str) and value in registered:
            return value
        members = [member.value for member in enum_type]
        raise ValueError(
            f"{value!r} is neither in {enum_type.__name__} nor registered under "
            f"{category!r}. {enum_type.__name__} members: {members}. Registered "
            f"{category!r} names: {sorted(registered)}. Modules listed in 'plugins' "
            "register their names before this check."
        ) from None


def _coerce_value(field_type: Any, value: Any) -> Any:
    """Coerce a raw TOML/CLI value to the expected field type."""
    origin = get_origin(field_type)

    if origin is types.UnionType or origin is Union:
        args = get_args(field_type)
        non_none = [a for a in args if a is not type(None)]
        if value is None:
            return None
        if len(non_none) == 1:
            return _coerce_value(non_none[0], value)
        return value

    if origin is Literal:
        allowed = get_args(field_type)
        if value not in allowed:
            raise ValueError(f"Value {value!r} not in allowed Literal values: {allowed}")
        return value

    if isinstance(field_type, type) and issubclass(field_type, Enum):
        if isinstance(value, field_type):
            return value
        if field_type in _REGISTRY_ENUMS:
            return _coerce_registry_enum(field_type, _REGISTRY_ENUMS[field_type], value)
        return field_type(value)

    if origin is tuple:
        if isinstance(value, (list, tuple)):
            args = get_args(field_type)
            if (
                len(args) == 2
                and args[1] is Ellipsis
                and isinstance(args[0], type)
                and is_dataclass(args[0])
            ):
                dc_type = args[0]
                return tuple(
                    _instantiate_from_dict(dc_type, item) if isinstance(item, dict) else item
                    for item in value
                )
            if all(isinstance(a, type) and is_dataclass(a) for a in args) and len(args) == len(
                value
            ):
                return tuple(
                    _instantiate_from_dict(dc_type, item) if isinstance(item, dict) else item
                    for dc_type, item in zip(args, value, strict=True)
                )
            return tuple(value)
        return value

    if origin is list:
        if isinstance(value, list):
            args = get_args(field_type)
            if args and isinstance(args[0], type) and is_dataclass(args[0]):
                dc_type = args[0]
                return [
                    _instantiate_from_dict(dc_type, item) if isinstance(item, dict) else item
                    for item in value
                ]
            return value
        return [value]

    if origin is dict and isinstance(value, dict) and len(get_args(field_type)) == 2:
        value_type = get_args(field_type)[1]
        coerced = {}
        for key, item in value.items():
            try:
                coerced[key] = _coerce_value(value_type, item)
            except ValueError as e:
                raise ValueError(f"key {key!r}: {e}") from None
        return coerced

    if field_type is bool:
        return _coerce_bool(value)
    if field_type is int or field_type is float:
        return _coerce_number(field_type, value)

    return value


_BOOL_SPELLINGS = {"true": True, "1": True, "yes": True, "false": False, "0": False, "no": False}


def _coerce_bool(value: Any) -> bool:
    """A bool from a bool, the number 0 or 1, or a true or false spelling in any case.

    Raises:
        ValueError: Any other value, a misspelling included.
    """
    if isinstance(value, bool):
        return value
    if isinstance(value, str) and value.lower() in _BOOL_SPELLINGS:
        return _BOOL_SPELLINGS[value.lower()]
    if isinstance(value, (int, float)) and value in (0, 1):
        return bool(value)
    raise ValueError(f"expected a bool (true or false), got {value!r}")


def _coerce_number(field_type: type[int] | type[float], value: Any) -> int | float:
    """An int or a float from a number or a numeric string.

    Raises:
        ValueError: A bool, a string that is not such a number, a value of another type,
            for an int, a number with a fraction, or, for a float, an int too large for one.
    """
    article = "an" if field_type is int else "a"
    refusal = f"expected {article} {field_type.__name__}, got {value!r}"
    fractional = isinstance(value, float) and not value.is_integer()
    if isinstance(value, bool) or not isinstance(value, (str, int, float)):
        raise ValueError(refusal)
    if field_type is int and fractional:
        raise ValueError(refusal)
    try:
        return field_type(value)
    except (ValueError, OverflowError):
        raise ValueError(refusal) from None


def _coerce_field(dc_type: type, name: str, hint: Any, raw: Any) -> Any:
    """``_coerce_value`` for the field ``name`` of ``dc_type``, whose errors name it."""
    try:
        return _coerce_value(hint, raw)
    except ValueError as e:
        raise ValueError(f"{dc_type.__name__}.{name}: {e}") from None


_type_hints_cache: dict[type, dict[str, Any]] = {}


def _get_type_hints(dc_type: type) -> dict[str, Any]:
    """Get resolved type hints for a dataclass, with caching."""
    if dc_type not in _type_hints_cache:
        _type_hints_cache[dc_type] = get_type_hints(dc_type)
    return _type_hints_cache[dc_type]


def _dataclass_type_from_hint(hint: Any) -> type | None:
    """Return the dataclass type inside ``hint`` if the hint is a dataclass
    or ``dataclass | None`` (Optional[dataclass]). Returns ``None`` otherwise.
    """
    origin = get_origin(hint)
    if origin is types.UnionType or origin is Union:
        for arg in get_args(hint):
            if arg is type(None):
                continue
            if isinstance(arg, type) and is_dataclass(arg):
                return arg
        return None
    if isinstance(hint, type) and is_dataclass(hint):
        return hint
    return None


class _DottedKeys(dict):
    """The keys a dotted CLI override names below a config field, unlike a dict literal.

    ``_parse_cli_overrides`` builds these for dotted paths, so a dotted key below a
    dict-valued field sets that key and keeps the rest of the field's table.
    """


def _with_dotted_keys(table: dict[str, Any], keys: dict[str, Any]) -> dict[str, Any]:
    """``table`` with the keys a dotted override sets, the rest of it kept.

    A dotted key below one of ``table``'s own tables sets that key in it in turn; any other
    value, a dict literal included, replaces the one ``table`` holds. The result holds plain
    dicts only.
    """
    merged = dict(table)
    for key, value in keys.items():
        if isinstance(value, dict):
            below = merged.get(key) if isinstance(value, _DottedKeys) else None
            value = _with_dotted_keys(below if isinstance(below, dict) else {}, value)
        merged[key] = value
    return merged


def _dict_field_value(raw: dict[str, Any], current: Any) -> dict[str, Any]:
    """The table a dict ``raw`` gives a field that holds ``current``.

    A dotted override sets its keys in ``current``'s table and keeps the rest; a dict
    literal, as from a TOML table, replaces it.
    """
    table = current if isinstance(raw, _DottedKeys) and isinstance(current, dict) else {}
    return _with_dotted_keys(table, raw)


def _instantiate_from_dict(dc_type: type, data: dict[str, Any]) -> Any:
    """Construct a dataclass directly from a dict, without first building a
    default instance.

    A field ``data`` leaves out takes its declared default, so a default that
    ``__post_init__`` derives from other fields, such as ``ModelConfig.n_kv_heads``
    from ``n_heads``, reads the values ``data`` gives them. A dataclass field that
    ``data`` gives a dict is built the same way; ``load_config`` builds the whole
    config with this function.

    When ``dc_type`` is ``VLMConfig`` (the discriminated-union base),
    dispatch on the ``arch`` field to the registered subclass before
    populating fields, so subclass-specific fields (e.g.
    ``cross_attention_every_n_layers``) are recognized.

    Raises:
        ValueError: ``data`` holds a key ``dc_type`` does not declare, which catches
            typos early, a value its field cannot take, or settings a
            ``__post_init__`` check refuses.
    """
    if dc_type is VLMConfig:
        dc_type = _resolve_vlm_subclass(data)
    type_hints = _get_type_hints(dc_type)
    field_names = {f.name for f in fields(dc_type)}
    unknown = set(data.keys()) - field_names
    if unknown:
        raise ValueError(
            f"Unknown config keys in {dc_type.__name__}: {sorted(unknown)}. "
            f"Valid keys: {sorted(field_names)}"
        )
    kwargs: dict[str, Any] = {}
    for f in fields(dc_type):
        if f.name not in data:
            continue
        raw = data[f.name]
        hint = type_hints[f.name]
        inner = _dataclass_type_from_hint(hint)
        if inner is not None and isinstance(raw, dict):
            kwargs[f.name] = _instantiate_from_dict(inner, raw)
        elif isinstance(raw, dict):
            default = None
            if isinstance(raw, _DottedKeys):
                default = f.default_factory() if callable(f.default_factory) else f.default
            kwargs[f.name] = _coerce_field(dc_type, f.name, hint, _dict_field_value(raw, default))
        else:
            kwargs[f.name] = _coerce_field(dc_type, f.name, hint, raw)
    return dc_type(**kwargs)


def _resolve_vlm_subclass(data: dict[str, Any]) -> type:
    """Resolve a TOML ``[vlm]`` table to the right ``VLMConfig`` subclass
    via the registered-arch lookup.

    An unregistered arch raises the same ``ValueError`` as
    ``VLMConfig.for_arch``, whichever site constructs the config.
    """
    arch = data.get("arch", "joint_decoder")
    try:
        return registry.get_vlm_config(arch)
    except KeyError as e:
        raise ValueError(
            f"Unknown vlm.arch: {arch!r}. Registered: {sorted(registry.list_vlm_configs())}."
        ) from e


def _check_vlm_arch_override(built: type[VLMConfig], arch: Any) -> None:
    """Reject an ``arch`` override whose registered config class is not ``built``.

    ``built`` is the class the ``[vlm]`` table's own ``arch`` selects, and the
    table's other keys were written for it, so an override keeps that class.
    """
    target = _resolve_vlm_subclass({"arch": arch})
    if target is not built:
        raise ValueError(
            f"vlm.arch={arch!r} cannot be applied as an override: the [vlm] section was "
            f"built as {built.__name__} (arch {built.declared_arch()!r}), and an "
            f'override keeps that class. Set arch = "{arch}" in the TOML\'s [vlm] '
            "section instead."
        )


def _overlay(dc_type: type, base: dict[str, Any], top: dict[str, Any]) -> dict[str, Any]:
    """``base``, a table for a ``dc_type``, with the parsed overrides ``top`` laid over it.

    A dict below a dataclass field merges key by key into ``base``'s table for it, a dotted
    key below a dict-valued field sets that key in ``base``'s table, and any other value
    replaces ``base``'s. A key ``base`` does not hold keeps ``top``'s value as it is, so
    building the config lays dotted keys over the field's default. Nothing is built, so no
    ``__post_init__`` check runs here.

    Raises:
        ValueError: ``base`` is a ``[vlm]`` table whose ``arch`` is not registered, or
            ``top`` sets an ``arch`` that needs another config class than ``base``'s.
    """
    if dc_type is VLMConfig:
        dc_type = _resolve_vlm_subclass(base)
        if "arch" in top:
            _check_vlm_arch_override(dc_type, top["arch"])
    type_hints = _get_type_hints(dc_type)
    merged = dict(base)
    for key, value in top.items():
        below = merged.get(key)
        if isinstance(value, dict) and isinstance(below, dict) and key in type_hints:
            inner = _dataclass_type_from_hint(type_hints[key])
            if inner is not None:
                value = _overlay(inner, below, value)
            elif isinstance(value, _DottedKeys):
                value = _with_dotted_keys(below, value)
        merged[key] = value
    return merged


def _parse_cli_overrides(args: list[str]) -> dict[str, Any]:
    """Parse --section.key=value CLI arguments into a nested dict.

    Supports:
      --model.dim=512
      --train.compile_model=true
      --train.compile_model (a bare key means true)
      --optimizer.betas=[0.9,0.95]

    Arguments without ``--`` before the first override are skipped, such as the
    config path when ``load_config`` reads ``sys.argv[1:]``.

    Raises:
        ValueError: An argument without ``--`` follows an override. After a bare key
            it is the value of a space-separated ``--section.key value``, which would
            otherwise be dropped while the key read as true; after a complete override
            it is the rest of a value with a space that a shell split off, which would
            otherwise be dropped from the value. The message shows the override with
            the arguments up to the next override joined back, quoted for a shell.
    """
    overrides: dict[str, Any] = {}

    flag: str | None = None
    for i, arg in enumerate(args):
        if not arg.startswith("--"):
            if flag is not None:
                rest = " ".join(itertools.takewhile(lambda a: not a.startswith("--"), args[i:]))
                joined = f"{flag} {rest}" if "=" in flag else f"{flag}={rest}"
                raise ValueError(
                    f"Unexpected command-line argument {arg!r} after {flag}: "
                    f"write {shlex.quote(joined)}"
                )
            continue
        flag = arg
        if "=" not in arg:
            key = arg[2:]
            value_str = "true"
        else:
            key, value_str = arg[2:].split("=", 1)

        value: Any
        try:
            value = ast.literal_eval(value_str)
        except (ValueError, SyntaxError):
            value = value_str

        parts = key.split(".")
        d = overrides
        for part in parts[:-1]:
            d = d.setdefault(part, _DottedKeys())
        d[parts[-1]] = value

    return overrides


def _plugin_module_names(raw: Any) -> list[str]:
    """Normalize a raw ``plugins`` value to a list of module paths."""
    names = [raw] if isinstance(raw, str) else raw
    if not isinstance(names, list) or not all(isinstance(n, str) for n in names):
        raise ValueError(
            "Config key 'plugins' must be a list of module paths "
            f'(e.g. plugins = ["my_experiment.components"]); got {raw!r}'
        )
    return names


def _plugin_not_found(error: Exception, name: str) -> bool:
    """Whether ``error`` says the plugin module ``name``, or a package above it, was not found."""
    if not isinstance(error, ModuleNotFoundError) or error.name is None:
        return False
    parts = name.split(".")
    return error.name in {".".join(parts[: i + 1]) for i in range(len(parts))}


def _import_plugins(raw: Any) -> None:
    """Import config-declared modules for their registry side effects.

    ``import_module`` is idempotent, so repeated ``load_config`` calls in one
    process never re-run a module body. A module that fails to import raises a
    ``ValueError`` naming it. The ``sys.path`` hint is added only when the module
    itself, or a package above it, was not found; any other failure, a missing
    dependency of the module included, means the module was found.
    """
    for name in _plugin_module_names(raw):
        try:
            importlib.import_module(name)
        except Exception as e:
            hint = (
                " Plugin modules must be on sys.path (the launch directory is not): add "
                "their directory to PYTHONPATH, or install them."
                if _plugin_not_found(e, name)
                else ""
            )
            raise ValueError(
                f"Failed to import plugin module {name!r} from config key 'plugins': "
                f"{type(e).__name__}: {e}.{hint}"
            ) from e


[docs] def load_toml(path: str | Path) -> dict[str, Any]: """Load a TOML file and return its contents as a dict.""" path = Path(path) if not path.exists(): raise FileNotFoundError(f"Config file not found: {path}") with open(path, "rb") as f: return tomllib.load(f)
[docs] def load_config( config_path: str | Path | None = None, cli_args: list[str] | None = None, ) -> JobConfig: """Load a JobConfig from optional TOML file + CLI overrides. The returned config has all sub-config __post_init__ validations applied. They run once, on the TOML with the CLI overrides laid over it, so a check that compares fields reads them whichever layer sets each. Each section is built from its field defaults and the merged layers, so a default that ``__post_init__`` derives from other fields, such as ``model.n_kv_heads`` from ``model.n_heads``, follows them whichever layer sets them. Cross-config validation (e.g., parallelism vs world_size) requires calling config.validate(world_size=...) separately at distributed setup time. Modules named by the top-level ``plugins`` key are imported before the overlay, so components they register are visible to those validations. Args: config_path: Path to a TOML config file (or None for defaults). cli_args: CLI arguments to parse (defaults to sys.argv[1:]). Returns: A JobConfig with layered defaults โ†’ TOML โ†’ CLI overrides. """ toml_data: dict[str, Any] = load_toml(config_path) if config_path is not None else {} if cli_args is None: cli_args = sys.argv[1:] overrides = _parse_cli_overrides(cli_args) plugins = overrides.get("plugins", toml_data.get("plugins")) if plugins is not None: _import_plugins(plugins) return _instantiate_from_dict(JobConfig, _overlay(JobConfig, toml_data, overrides))