Core foundations

Typed registries, normalization helpers, deterministic utilities, image composition, and reusable safety guardrail protocols.

On this page

Foundational Core APIs are small, but they define conventions shared by many larger systems: normalized identifiers, deterministic registries, environment flags, exact division, common list conversion, image materialization/composition, random seeding, and safety interfaces.

Typed registry example

from worldfoundry.core import TypedRegistry

metrics = TypedRegistry()
metrics.register(
    "temporal-consistency",
    object(),
    aliases=("temporal", "tc"),
    metadata={"direction": "higher-is-better"},
)

assert metrics.get("TC") is metrics.get("temporal-consistency")
assert metrics.keys() == ("temporal-consistency",)

Keys and aliases use stripped, case-folded lookup, while the original public key remains in RegistryItem. Registration rejects collisions instead of silently overwriting them. Enumeration is deterministic, which makes generated manifests and tests stable.

Guardrail composition example

from worldfoundry.core.safety import GuardrailRunner

class RejectEmptyPrompt:
    def is_safe(self, value):
        prompt = str(value).strip()
        return (bool(prompt), "prompt is empty" if not prompt else "")

runner = GuardrailRunner(
    safety_models=[RejectEmptyPrompt()],
    generic_block_msg="Request rejected",
)

assert runner.run_safety_check("walk through a snowy forest")[0] is True
assert runner.run_safety_check("") == (False, "Request rejected")

ContentSafetyGuardrail and PostprocessingGuardrail are structural protocols: implementations only need the documented method. GuardrailRunner stops at the first unsafe classifier, then applies postprocessors sequentially when requested. An empty classifier list returns safe with a warning; production policy should decide explicitly whether that fail-open behavior is acceptable.

The safety package imports NumPy and rank-aware Loguru logging from the model runtime environment. The registry example itself uses only the import-light top-level Core facade.

Utility boundaries

env_is_true recognizes a bounded truthy vocabulary; it is not a general parser. divide asserts exact divisibility and is intended for shape/group invariants. as_list normalizes a scalar or sequence at API boundaries. set_random_seed coordinates common random backends but does not by itself guarantee deterministic CUDA kernels.

Image helpers accept paths, PIL images, arrays, or tensors where documented. compose_horizontal_views and split_horizontal_views preserve a named view ordering; keep that ordering with the resulting artifact instead of relying on a later reader to guess it.

Complete reference

The blocks below are the generated signatures for this category. Use the on-page symbol index to jump; source links open the defining implementation behind each lazy export.

23 public symbols

def as_list(value,*,none_as_empty: bool = True) -> list
worldfoundry.corefrom worldfoundry.core import as_list

Normalize optional scalar or sequence values into a plain list. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: list.

Parameters

value
none_as_emptybooldefault True

Returns

list
class ContentSafetyGuardrail(Protocol)
worldfoundry.core.safetyfrom worldfoundry.core.safety import ContentSafetyGuardrail

Interface implemented by prompt and media safety classifiers. Belongs to Core foundations (registries, utilities, safety contracts).

Methods

methis_safe(input: Any) -> tuple[bool, str]Source

Return whether `input` is safe and an optional explanation.

Parameters

inputAny

Returns

tuple[bool, str]
def cuda_visible_devices_from_device(device: str | torch.device | None,*,inherited: str | None = None,map_inherited: bool = True,default_cuda: str = '0') -> str | None
worldfoundry.corefrom worldfoundry.core import cuda_visible_devices_from_device

Overview

Convert a device string into a `CUDA_VISIBLE_DEVICES value. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: str | None`.

Source docstring

Convert a device string into a `CUDA_VISIBLE_DEVICES` value.

`cuda:N is interpreted as a local index into an inherited CUDA_VISIBLE_DEVICES` list by default, which is the behavior expected by subprocess launchers nested under a scheduler or torchrun process.

Parameters

devicestr | torch.device | None
inheritedstr | Nonedefault None
map_inheritedbooldefault True
default_cudastrdefault '0'

Returns

str | None
function

divide

Source
def divide(numerator: int,denominator: int) -> int
worldfoundry.corefrom worldfoundry.core import divide

Return exact integer division and reject a non-divisible numerator. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: int.

Parameters

numeratorint
denominatorint

Returns

int

Raises

AssertionError
`numerator is not divisible by denominator`.
worldfoundry.corefrom worldfoundry.core import DuplicateRegistryKeyError

Raised when a key or alias maps to multiple different entries. Belongs to Core foundations (registries, utilities, safety contracts).

def env_is_true(env_name: str) -> bool
worldfoundry.corefrom worldfoundry.core import env_is_true

Return whether an environment variable uses a recognized truthy spelling. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: bool.

Parameters

env_namestr

Returns

bool
def get_current_torch_device() -> torch.device
worldfoundry.corefrom worldfoundry.core import get_current_torch_device

Overview

Return the accelerator selected for this process, or CPU. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: torch.device.

Source docstring

Return the accelerator selected for this process, or CPU.

Distributed launchers select a process-local device with `set_device`. Using that current index avoids collapsing every local rank onto CUDA 0.

Returns

torch.device
class GuardrailRunner(safety_models: Sequence[ContentSafetyGuardrail] | None = None,generic_block_msg: str = '',generic_safe_msg: str = '',postprocessors: Sequence[PostprocessingGuardrail] | None = None)
worldfoundry.core.safetyfrom worldfoundry.core.safety import GuardrailRunner

Run reusable safety classifiers and postprocessors in sequence. Belongs to Core foundations (registries, utilities, safety contracts).

Parameters

safety_modelsSequence[ContentSafetyGuardrail] | Nonedefault None
Ordered classifiers. Evaluation stops on the first unsafe result.
generic_block_msgstrdefault ''
Optional public message replacing classifier details when a request is blocked.
generic_safe_msgstrdefault ''
Message returned after all classifiers pass.
postprocessorsSequence[PostprocessingGuardrail] | Nonedefault None
Ordered frame transforms applied by `postprocess`.

Methods

methrun_safety_check(input: Any) -> tuple[bool, str]Source

Overview

Run classifiers in order and return the first block or final safe result.

Source docstring

Run classifiers in order and return the first block or final safe result.

Note the deliberate fail-open default: with no configured safety models the input is reported safe (with a warning). Deployments that require enforcement must configure at least one classifier.

Parameters

inputAny

Returns

tuple[bool, str]
methpostprocess(frames: np.ndarray) -> np.ndarraySource

Apply every configured safety postprocessor to a frame array.

Parameters

framesnp.ndarray

Returns

np.ndarray
def mean_flat(tensor: torch.Tensor) -> torch.Tensor
worldfoundry.corefrom worldfoundry.core import mean_flat

Average a tensor over all non-batch dimensions — common in diffusion losses.

Parameters

tensortorch.Tensor

Returns

torch.Tensor
def normalize_action_values(values: Any,statistics: Mapping[str, Any],*,mode: str = 'min_max',clip: float | None = None) -> np.ndarray
worldfoundry.corefrom worldfoundry.core import normalize_action_values

Normalize action values using checkpoint statistics along the last axis. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: np.ndarray.

Parameters

valuesAny
Array-like with at least one dimension. The last axis is the action width and must match each statistic vector.
statisticsMapping[str, Any]
Selected modality mapping from :func:select_modality_statistics.
modestrdefault 'min_max'
`min_max (default), q99 / quantile / bounds, mean_std / standard / zscore, or identity`.
clipfloat | Nonedefault None
When set, clamp masked channels to `[-clip, clip]` after normalization.

Returns

np.ndarrayA writable `float` array with the same shape as *values*.
def normalize_registry_key(value: str,*,field_name: str = 'registry key') -> str
worldfoundry.corefrom worldfoundry.core import normalize_registry_key

Strip and `casefold a user-facing Registry key for case-insensitive lookup. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: str`.

Parameters

valuestr
field_namestrdefault 'registry key'

Returns

str
class PostprocessingGuardrail(Protocol)
worldfoundry.core.safetyfrom worldfoundry.core.safety import PostprocessingGuardrail

Interface implemented by safety postprocessors such as face blurring. Belongs to Core foundations (registries, utilities, safety contracts).

Methods

methpostprocess(frames: np.ndarray) -> np.ndarraySource

Return safety-processed frames.

Parameters

framesnp.ndarray

Returns

np.ndarray
worldfoundry.corefrom worldfoundry.core import PromptProcessor

Overview

Apply optional prompt refiners and extenders without owning model loading. Belongs to Core foundations (registries, utilities, safety contracts).

Source docstring

Apply optional prompt refiners and extenders without owning model loading.

`refiners rewrite a string or list in place; extenders take a {"prompt": ...} mapping and return an expanded dict. Both run under torch.no_grad()`.

Methods

methload_prompt_refiners(model_source: Any,refiner_classes: Sequence[type[_PromptHookFactory]] = ()) -> NoneSource

Instantiate each refiner with `from_model_manager(model_source)` and append it.

Parameters

model_sourceAny
refiner_classesSequence[type[_PromptHookFactory]]default ()

Returns

None
methload_prompt_extenders(model_source: Any,extender_classes: Sequence[type[_PromptHookFactory]] = ()) -> NoneSource

Instantiate each extender with `from_model_manager(model_source)` and append it.

Parameters

model_sourceAny
extender_classesSequence[type[_PromptHookFactory]]default ()

Returns

None
methprocess_prompt(prompt,positive: bool = True)Source

Run refiners in order on one prompt or a list; lists are processed recursively.

Parameters

prompt
positivebooldefault True
methextend_prompt(prompt: str,positive: bool = True)Source

Overview

Wrap `prompt as {"prompt": ...}` and run extenders in order.

Source docstring

Wrap `prompt as {"prompt": ...}` and run extenders in order.

`positive` is kept only to match the refiner API; this implementation does not use it.

Parameters

promptstr
positivebooldefault True
worldfoundry.corefrom worldfoundry.core import RegistryError

Base class for registry definition errors. Belongs to Core foundations (registries, utilities, safety contracts).

class RegistryItem(key: str,value: ItemT,aliases: tuple[str, ...] = (),metadata: Mapping[str, object] = <dict factory>)
worldfoundry.corefrom worldfoundry.core import RegistryItem

One registered item plus its public aliases. Belongs to Core foundations (registries, utilities, safety contracts).

Attributes

keystr
valueItemT
aliasestuple[str, ...]default ()
metadataMapping[str, object]default <dict factory>
def resolve_inference_device(device: str | torch.device | None = 'cuda',*,allow_cpu_fallback: bool = False) -> str
worldfoundry.corefrom worldfoundry.core import resolve_inference_device

Overview

Resolve a concrete inference device without silently selecting the wrong GPU. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: str.

Source docstring

Resolve a concrete inference device without silently selecting the wrong GPU.

Bare `cuda resolves to the CUDA device currently selected for this process. Explicit indices are preserved, which is important when a caller deliberately selects (for example) cuda:4` under an eight-GPU workspace.

Parameters

devicestr | torch.device | Nonedefault 'cuda'
allow_cpu_fallbackbooldefault False

Returns

str
def resolve_inference_dtype(device: str | torch.device,dtype: str | torch.dtype | None = 'auto',*,strict: bool = True) -> torch.dtype
worldfoundry.corefrom worldfoundry.core import resolve_inference_dtype

Overview

Resolve an inference dtype using the selected accelerator's capability. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: torch.dtype.

Source docstring

Resolve an inference dtype using the selected accelerator's capability.

`auto` selects bf16 on Ampere/Hopper/Blackwell-or-newer CUDA devices, fp16 on older CUDA devices, and fp32 on CPU. Explicit unsupported bf16 is rejected in strict mode instead of producing a later kernel failure.

Parameters

devicestr | torch.device
dtypestr | torch.dtype | Nonedefault 'auto'
strictbooldefault True

Returns

torch.dtype
def select_modality_statistics(dataset_statistics: Mapping[str, Any],*,modality: str = 'action',key: str | None = None) -> tuple[str | None, Mapping[str, Any]]
worldfoundry.corefrom worldfoundry.core import select_modality_statistics

Overview

Select one modality's statistics from a checkpoint statistics mapping. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: tuple[str | None, Mapping[str, Any]].

Source docstring

Select one modality's statistics from a checkpoint statistics mapping.

Both common layouts are accepted: a direct `{"min": ..., "max": ...} mapping and a dataset-keyed {"robot": {"action": {...}}}` mapping. Dataset-key selection is strict when more than one key is available.

Parameters

dataset_statisticsMapping[str, Any]
Checkpoint statistics mapping.
modalitystrdefault 'action'
Nested key under a dataset entry (default `"action"`).
keystr | Nonedefault None
Dataset name when *dataset_statistics* is multi-key. Omit only when a single key (or a direct stats mapping) is present.

Returns

tuple[str | None, Mapping[str, Any]]`(resolved_key, stats_mapping). *resolved_key* is None` when the input was already a direct statistics mapping.

Raises

KeyError
*key* is missing or has no *modality* mapping.
ValueError
Empty input, or multiple dataset keys with no *key*.
def set_random_seed(seed: int,by_rank: bool = False) -> int
worldfoundry.corefrom worldfoundry.core import set_random_seed

Overview

Set Python, NumPy, and PyTorch seeds with optional distributed-rank offset. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: int.

Source docstring

Set Python, NumPy, and PyTorch seeds with optional distributed-rank offset.

Thin wrapper over :func:set_seed_everywhere (the canonical entry point). When the process group is unavailable, `by_rank` silently falls back to the unoffset seed.

Parameters

seedint
by_rankbooldefault False

Returns

int
def stack_or_pad_tensors(values: Sequence[Tensor],*,padding_value: float | int | bool | None = None) -> Tensor
worldfoundry.corefrom worldfoundry.core import stack_or_pad_tensors

Overview

Stack equal tensors or right-pad variable-length 1-D tensors. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: Tensor.

Source docstring

Stack equal tensors or right-pad variable-length 1-D tensors.

This is the common collation shape used by multimodal policies whose dense image/state inputs are fixed while token and mask lengths may vary. More complex shape mismatches are rejected instead of being padded silently.

Parameters

valuesSequence[Tensor]
padding_valuefloat | int | bool | Nonedefault None

Returns

Tensor
class TypedRegistry(items: Iterable[RegistryItem[ItemT]] = ())
worldfoundry.corefrom worldfoundry.core import TypedRegistry

Overview

Deterministic keyed registry with alias support. Belongs to Core foundations (registries, utilities, safety contracts).

Source docstring

Deterministic keyed registry with alias support.

Registration methods (mutate state): - `register(key, value, ...)` — add one item and its aliases.

Lookup methods (read state): - `get(key) / get_item(key) — resolve a key or alias. - keys / values / items / aliases` — enumerate entries.

Parameters

itemsIterable[RegistryItem[ItemT]]default ()

Raises

DuplicateRegistryKeyError
On conflicting keys or aliases.
UnknownRegistryKeyError
When a lookup cannot be resolved.

Methods

methregister(key: str,value: ItemT,*,aliases: Iterable[str] = (),metadata: Mapping[str, object] | None = None) -> RegistryItem[ItemT]Source

Register an item and return the normalized registry record.

Parameters

keystr
valueItemT
aliasesIterable[str]default ()
metadataMapping[str, object] | Nonedefault None

Returns

methget(key: str) -> ItemTSource

Resolve a key or alias to the registered value.

Parameters

keystr

Returns

ItemT
methget_item(key: str) -> RegistryItem[ItemT]Source

Resolve a key or alias to the full registry item.

Parameters

keystr

Returns

methkeys() -> tuple[str, ...]Source

Return canonical keys in deterministic order.

Returns

tuple[str, ...]
methaliases() -> Mapping[str, str]Source

Return normalized alias to normalized canonical key mapping.

Returns

Mapping[str, str]
methitems() -> tuple[RegistryItem[ItemT], ...]Source

Return registry items sorted by their public key.

Returns

tuple[RegistryItem[ItemT], ...]
methvalues() -> tuple[ItemT, ...]Source

Return registered values sorted by public key.

Returns

tuple[ItemT, ...]
worldfoundry.corefrom worldfoundry.core import UnknownRegistryKeyError

Raised when a registry lookup cannot be resolved. Belongs to Core foundations (registries, utilities, safety contracts).

def unnormalize_action_values(normalized_values: Any,statistics: Mapping[str, Any],*,mode: str = 'min_max') -> np.ndarray
worldfoundry.corefrom worldfoundry.core import unnormalize_action_values

Overview

Convert normalized policy outputs back to environment-space actions. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: np.ndarray.

Source docstring

Convert normalized policy outputs back to environment-space actions.

Inverse of :func:normalize_action_values for the same *mode* and *statistics*. Masked-off channels are copied through unchanged. Unlike the forward path, this function does not clip.

Parameters

normalized_valuesAny
Policy outputs in the normalized space.
statisticsMapping[str, Any]
Same modality mapping used at normalize time.
modestrdefault 'min_max'
Must match the mode used to produce *normalized_values*.

Returns

np.ndarrayEnvironment-space actions with the same shape as the input.