Skip to content
SR-Forge

Config

Configuration utilities.

ConfigParser

Bases: ConfigResolver

Config resolver with training-specific lifecycle methods.

.. deprecated:: Use :class:~srforge.config.resolver.ConfigResolver for generic config resolution. ConfigParser will be removed in a future release.

Extends :class:ConfigResolver with model/optimizer/scheduler instantiation, W&B checkpoint loading, and training resume support.

Parameters:

Name Type Description Default
config CONFIG_TYPE

Root configuration object.

required
run Run

W&B run handle.

required

__get_stored_file(file: str) -> Any

Restore a file from W&B and load it with torch.

Parameters:

Name Type Description Default
file str

File name to restore.

required

Returns:

Type Description
Any

Loaded object from the restored file.

__dict_to_params_list(config: Union[ListConfig[CONFIG_TYPE], CONFIG_TYPE]) -> Union[ListConfig, CONFIG_TYPE] staticmethod

Normalize a config object into a list wrapper.

Parameters:

Name Type Description Default
config Union[ListConfig[CONFIG_TYPE], CONFIG_TYPE]

Config to normalize.

required

Returns:

Type Description
Union[ListConfig, CONFIG_TYPE]

The normalized config.

get_model() -> torch.nn.Module

Instantiate the model defined in the config.

Returns:

Type Description
Module

Instantiated model.

Raises:

Type Description
FileNotFoundError

If requested resume weights are missing.

get_optimizer() -> torch.optim.Optimizer

Instantiate the optimizer defined in the config.

The optimizer's params (model parameters) should be declared in the config via %{model}.trainable_params() or %{model}.parameters().

Returns:

Type Description
Optimizer

Instantiated optimizer.

get_lr_scheduler() -> torch.optim.lr_scheduler.LRScheduler

Instantiate the learning rate scheduler defined in the config.

The scheduler's optimizer should be declared in the config via %{optimizer}. When no scheduler config is provided, a :class:BlankLRScheduler is used.

Returns:

Type Description
LRScheduler

Instantiated scheduler.

get_training_data() -> tuple

Return resume-related training metadata.

Returns:

Type Description
tuple

tuple[int, Any]: Initial epoch and best losses (if resuming).

ConfigResolver

Resolve OmegaConf configs into live Python objects.

Config syntax::

_target: module.ClassName   # or a ClassRegistry short name
params:
    param1: value1
    param2: value2
io:                         # optional, only for IOModule subclasses
    inputs: {port: field}
    outputs: field

Reference syntax (preferred — no quoting needed in YAML)::

${ref:path.to.object}                # resolve a previously instantiated object
${ref:model}.method()                # resolve + call a no-arg method
${ref:model}.foo().bar()             # chained method calls

Legacy syntax (requires YAML quoting)::

"%{path.to.object}"                  # resolve a previously instantiated object
"%{path.to.object}.method()"         # resolve + call a no-arg method

resolve_all() -> dict[str, Any]

Resolve all top-level config fields.

Returns:

Type Description
dict[str, Any]

Mapping of top-level keys to resolved objects.

audit() -> list[IndirectionEdge]

Return every static indirection edge in the config.

The list is computed once at construction time as a property of the precomputed :class:ConfigGraph; this method is a property lookup, not a traversal. Includes both _target dispatches (resolved to "module.ClassName" when determinable) and ${ref:...} references (resolved to the referenced config path).

__call__(config: Any, *args: Any, **kwargs: Any) -> Any

Parse and instantiate a config node.

Automatically registers the result in _instances when config is a node from this resolver's config tree, so ${ref:path} references resolve without manual bookkeeping.

Parameters:

Name Type Description Default
config Any

Config node to parse.

required
*args Any

Positional args to forward to the constructor.

()
**kwargs Any

Keyword args to forward to the constructor.

{}

Returns:

Type Description
Any

Parsed object.

Reference dataclass

Parsed view of a ${ref:path}.method() reference.

OmegaConf's ${ref:foo} custom resolver writes an internal %{foo} marker into the resolved config; this dataclass is the static parse of that marker plus any chained zero-argument method calls (e.g. ${ref:model}.trainable_params() produces Reference(path="model", methods=("trainable_params",))).

The reference syntax has two forms, both of which yield the same internal %{path}... marker:

  • ${ref:path.to.thing} — preferred unquoted form, registered as an OmegaConf resolver (see :mod:srforge.config.resolver module-level setup).
  • "%{path.to.thing}" — legacy quoted form, accepted for backwards compatibility.

Method chains must use zero-argument syntax only (.method1().method2()). Method dispatch happens at resolve time in :meth:ConfigResolver._resolve_reference_string, not here.

Attributes:

Name Type Description
path str

Dotted path through the config tree.

methods Tuple[str, ...]

Ordered tuple of zero-argument method names to call on the resolved object, empty when no method chain is present.

parse(value: Any) -> Optional['Reference'] classmethod

Return a :class:Reference when value is a reference marker string, else None.

Recognises both %{path} and %{path}.method().chain() forms; whitespace around the marker is tolerated. Any other input (non-string, plain text, or malformed marker) returns None.

Raises:

Type Description
ValueError

If the marker's path component is empty (%{}).

TargetSpec dataclass

Parsed view of a {_target, params, io} triple from a config node.

The target field is a string — either a fully-qualified Python path ("srforge.models.MISR.HighResNet") or a short name registered in :class:srforge.registry.ClassRegistry. The framework dispatches that string to a real Python class at runtime via :func:importlib.import_module + getattr, which is the single load-bearing string-to-class indirection point in sr-forge.

Use :meth:from_node to parse a config node into a spec without instantiating anything, and :meth:resolve_class to look up (module, class_name) for that target — useful for static audit tools and IDE plugins that need to follow the indirection without triggering side effects.

Attributes:

Name Type Description
target str

The raw value of the _target key.

params Mapping[str, Any]

The mapping under the params key, or an empty mapping when params is absent.

io Optional[Mapping[str, Any]]

The mapping under the io key, or None when absent.

from_node(node: Any) -> Optional['TargetSpec'] classmethod

Return a :class:TargetSpec when node looks like a _target-bearing config node, else None.

Accepts any mapping (DictConfig, plain dict, etc.) so the same parser works for both live OmegaConf trees and raw YAML loaded via :mod:yaml.safe_load. Returns None for nodes that are not mappings or that lack _target.

resolve_class(registry: Any = None) -> Tuple[str, str]

Return (module, class_name) for :attr:target.

Consults registry first for short-name lookups. When registry is None (the default), the singleton :class:srforge.registry.ClassRegistry is used.

Falls back to splitting :attr:target on the last dot when the registry does not contain the name. Empty module or class_name raise :class:ValueError.

Raises:

Type Description
ValueError

If :attr:target is missing or cannot be split into a valid module.ClassName pair.

import_class(registry: Any = None) -> type

Resolve :attr:target to an actual class object.

Convenience over :meth:resolve_class that performs the :func:importlib.import_module + getattr round-trip and returns the class. Mostly useful for diagnostic tools that want to inspect the resolved class without going through the full ConfigResolver pipeline.

Raises:

Type Description
ModuleNotFoundError

If the target module cannot be imported.

AttributeError

If the target class is missing from the resolved module.