Core 配置

延迟构造图、结构化推理配置、递归实例化与 freeze 行为。

本页内容

Core 配置把“描述对象图”和“构造昂贵模型对象”分开。LazyCall(target)(...) 会把 target 与命名参数记录成可编辑的 OmegaConf 节点;只有当 runtime 准备好以后,instantiate 才遍历对象图并真正创建对象。

这个 package 需要 attrs 和 omegaconf。它们由视频或模型 runtime 环境提供,不属于最小 CLI 安装。

延迟构造示例

from torch import nn

from worldfoundry.core.configuration import LazyCall, instantiate

Linear = LazyCall(nn.Linear)
layer_config = Linear(in_features=8, out_features=4, bias=False)

# 此时还没有真实 module,因此组合配置仍然可以修改对象图。
layer_config.out_features = 6
layer = instantiate(layer_config)

assert isinstance(layer, nn.Linear)
assert layer.in_features == 8
assert layer.out_features == 6

LazyCall 只接受关键字参数。它先记录 target 签名中的默认值,再用显式值覆盖。嵌套 list 和 mapping 默认递归实例化;设置 _recursive_=False 可以关闭递归;普通 mapping 和基础值会原样通过。

发布模型的结构化配置

Config 及其嵌套 attrs 类只保存发布推理共同需要的小部分配置:延迟模型图、checkpoint 来源、runtime/CuDNN 设置、模型并行设置和 job 身份。模型专属字段继续留在模型自己的 lazy graph 中。

make_freezable 会为采用 slots=False 的 attrs 类增加递归 freeze()。它用于防止配置完成组合后被意外改写,并不会让配置引用的 PyTorch module 也变成不可变对象。

完整参考

以下为该类别的生成签名。可用本页符号索引跳转;源码链接指向各惰性导出背后的具体实现。

9 个公开符号

class CheckpointConfig(load_path: str = '',load_from_object_store: ObjectStoreConfig = attrs.field(factory=ObjectStoreConfig),strict_resume: bool = True,dcp_allow_mismatched_size: bool = False,load_ema_to_reg: bool = False)
worldfoundry.core.configurationfrom worldfoundry.core.configuration import CheckpointConfig

CheckpointConfig — Checkpoint source and strictness controls for inference construction. 属于 Core 配置(LazyConfig / 延迟对象图)。

属性

load_pathstr默认值 ''
load_from_object_storeObjectStoreConfig默认值 attrs.field(factory=ObjectStoreConfig)
strict_resumebool默认值 True
dcp_allow_mismatched_sizebool默认值 False
load_ema_to_regbool默认值 False
class Config(model: LazyDict | None,job: JobConfig = attrs.field(factory=JobConfig),trainer: InferenceRuntimeConfig = attrs.field(factory=InferenceRuntimeConfig),model_parallel: Any = attrs.field(factory=_default_model_parallel),checkpoint: CheckpointConfig = attrs.field(factory=CheckpointConfig))
worldfoundry.core.configurationfrom worldfoundry.core.configuration import Config

Config — Fields used to compose and instantiate a released inference model. 属于 Core 配置(LazyConfig / 延迟对象图)。

属性

modelLazyDict | None
jobJobConfig默认值 attrs.field(factory=JobConfig)
trainerInferenceRuntimeConfig默认值 attrs.field(factory=InferenceRuntimeConfig)
model_parallelAny默认值 attrs.field(factory=_default_model_parallel)
checkpointCheckpointConfig默认值 attrs.field(factory=CheckpointConfig)

方法

methto_dict() -> dict[str, Any]源码

to_dict — Deep-copy this config tree into a plain dict (attrs `asdict`).

返回值

dict[str, Any]
methvalidate() -> None源码

validate — Validate the small set of fields needed during inference.

返回值

None
class EMAConfig(enabled: bool = False,rate: float = 0.1,iteration_shift: int = 0)
worldfoundry.core.configurationfrom worldfoundry.core.configuration import EMAConfig

EMAConfig — Exponential moving-average settings used while loading inference models. 属于 Core 配置(LazyConfig / 延迟对象图)。

属性

enabledbool默认值 False
ratefloat默认值 0.1
iteration_shiftint默认值 0
def instantiate(cfg,*args,**kwargs)
worldfoundry.core.configurationfrom worldfoundry.core.configuration import instantiate

简介

把 LazyConfig / LazyCall 对象图实例化为具体 Python 对象。

源码 docstring

Materialize a LazyCall / Hydra-style config into a live object.

Faster than `hydra.utils.instantiate(..., _convert_=all) for the common case of a mapping with _target_ (see facebookresearch/hydra #1200). Callers may pass extra *args / **kwargs`; keyword overrides win over stored config keys.

参数

cfg
A `_target_` mapping, OmegaConf container, list, or any already-materialized value.
args
Extra positional arguments forwarded to the target.
kwargs
Extra keyword arguments that override stored fields.

返回值

The constructed object, a list/ListConfig of constructed objects, a structured dataclass/attrs instance, or *cfg* unchanged when it is not a constructor description.
class LazyCall(target)
worldfoundry.core.configurationfrom worldfoundry.core.configuration import LazyCall

简介

LazyConfig 图中的延迟构造调用,对象只在 instantiate 时真正创建。

源码 docstring

Wrap a callable so that when it's called, the call will not be executed, but returns a dict that describes the call.

LazyCall object has to be called with only keyword arguments. Positional arguments are not yet supported.

Example:: from worldfoundry.core.configuration import LazyCall, instantiate

layer_cfg = LazyCall(nn.Conv2d)(in_channels=32, out_channels=32) layer_cfg.out_channels = 64 # can edit it afterwards layer = instantiate(layer_cfg)

参数

target
Callable to instantiate later, its importable string name, or an existing target mapping.

方法

meth__call__(**kwargs)源码

__call__ — Return an editable config instead of invoking the target.

参数

kwargs
Named constructor arguments. Target defaults are copied first, then explicit values override them.

返回值

OmegaConf `DictConfig containing _target_` and the eventual constructor arguments.

说明

Positional arguments are intentionally unsupported at this stage; they can be supplied later to `instantiate` when necessary.

class LazyConfig()
worldfoundry.core.configurationfrom worldfoundry.core.configuration import LazyConfig

简介

LazyConfig — Load local Python/YAML lazy configs and save resolved inference configs. 属于 Core 配置(LazyConfig / 延迟对象图)。

源码 docstring

Load local Python/YAML lazy configs and save resolved inference configs.

Trust boundary: `.py configs are executed (detectron2 LazyConfig design) -- only load Python configs you would run as code. YAML configs are parsed with yaml.safe_load and cannot instantiate arbitrary Python objects; save_yaml only ever emits plain YAML, so framework round-trips are unaffected. Configs needing Python objects belong in .py` files.

方法

smethload_rel(filename: str,keys: str | tuple[str, ...] | None = None)源码

简介

load_rel — Load a config relative to the *caller's* file, not the process cwd.

源码 docstring

Load a config relative to the *caller's* file, not the process cwd.

`inspect.stack()[1] is the caller. <string> (exec` without a filename) cannot resolve a sibling path and is rejected.

参数

filenamestr
keysstr | tuple[str, ...] | None默认值 None
smethload(filename: str,keys: str | tuple[str, ...] | None = None)源码

简介

load — Load a trusted `.py config via exec, or YAML via safe_load`.

源码 docstring

Load a trusted `.py config via exec, or YAML via safe_load`.

A `.py result drops names starting with _ and keeps only dict / OmegaConf values so helper functions defined in the file do not become config keys. keys` selects a subset after load.

参数

filenamestr
keysstr | tuple[str, ...] | None默认值 None

异常

SyntaxError
The Python config does not parse.
ValueError
Suffix is not `.py / .yaml / .yml`.
smethsave_yaml(config: Any,filename: str | Path) -> str源码

简介

save_yaml — Write a resolved, key-sorted YAML snapshot that cannot `exec`.

源码 docstring

Write a resolved, key-sorted YAML snapshot that cannot `exec`.

A failed `deepcopy is ignored so an un-copyable live object still serializes through :func:_plain_config` rather than aborting the save.

参数

configAny
filenamestr | Path

返回值

str
class LazyDict(*args,**kwargs)
worldfoundry.core.configurationfrom worldfoundry.core.configuration import LazyDict

简介

LazyDict — Marker subclass for editable, lazily instantiated object graphs. 属于 Core 配置(LazyConfig / 延迟对象图)。

源码 docstring

Marker subclass for editable, lazily instantiated object graphs.

It behaves like OmegaConf `DictConfig but lets WorldFoundry distinguish a deferred constructor tree from an ordinary runtime mapping. Construct it through LazyCall` in normal code.

参数

args
kwargs
def make_freezable(cls: T) -> T
worldfoundry.core.configurationfrom worldfoundry.core.configuration import make_freezable

简介

make_freezable — Add a recursive runtime `freeze operation to an attrs class. 属于 Core 配置(LazyConfig / 延迟对象图)。 标注返回类型:T`。

源码 docstring

Add a recursive runtime `freeze` operation to an attrs class.

Freezing is *shallow* with respect to containers: it blocks attribute assignment on the instance (and recursively freezes nested attrs values that expose `freeze`), but the contents of list/dict fields remain mutable. Decorating the same class twice is a no-op.

参数

clsT

返回值

T
class ObjectStoreConfig(enabled: bool = False,credentials: str = '',bucket: str = '')
worldfoundry.core.configurationfrom worldfoundry.core.configuration import ObjectStoreConfig

ObjectStoreConfig — Object-store location used to read inference checkpoints. 属于 Core 配置(LazyConfig / 延迟对象图)。

属性

enabledbool默认值 False
credentialsstr默认值 ''
bucketstr默认值 ''