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.core.as_listfrom worldfoundry.core import as_list
source

Overview

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_emptybool
default: True

Returns: list

def clear_inference_runtime_cache(cache: MutableMapping[Any, Any]) -> None
worldfoundry.core.clear_inference_runtime_cachefrom worldfoundry.core import clear_inference_runtime_cache
source

Overview

Drop cached runtimes and release unreferenced accelerator allocations. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: None.

Source docstring

Drop cached runtimes and release unreferenced accelerator allocations.

The torch import is intentionally lazy so model discovery remains cheap in processes that never execute a PyTorch policy. `empty_cache` only returns already-unreferenced blocks to the CUDA allocator; clearing the strong references and collecting cycles must happen first.

Parameters

cacheMutableMapping[Any, Any]

Returns: None

def compose_horizontal_views(images,target_size: tuple[int, int] | None = None) -> Image.Image
worldfoundry.core.compose_horizontal_viewsfrom worldfoundry.core import compose_horizontal_views
source

Overview

Resize optional per-view images and concatenate them horizontally. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: Image.Image.

Parameters

images
target_sizetuple[int, int] | None
default: None

Returns: Image.Image

class ContentSafetyGuardrail(Protocol)
worldfoundry.core.safety.ContentSafetyGuardrailfrom worldfoundry.core.safety import ContentSafetyGuardrail
source

Overview

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

Overview

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

Parameters

inputAny

Returns: tuple[bool, str]

divide

func
def divide(numerator: int, denominator: int) -> int
worldfoundry.core.dividefrom worldfoundry.core import divide
source

Overview

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

Raises

AssertionError
`numerator is not divisible by denominator`.

Returns: int

class DuplicateRegistryKeyError()
worldfoundry.core.DuplicateRegistryKeyErrorfrom worldfoundry.core import DuplicateRegistryKeyError
source

Overview

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.core.env_is_truefrom worldfoundry.core import env_is_true
source

Overview

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

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

Overview

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

Parameters

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

Methods

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

Overview

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

Parameters

inputAny

Returns: tuple[bool, str]

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

Overview

Apply every configured safety postprocessor to a frame array.

Parameters

framesnp.ndarray

Returns: np.ndarray

def load_pil_image(image_input, , first_sequence_item: bool = True) -> Image.Image
worldfoundry.core.load_pil_imagefrom worldfoundry.core import load_pil_image
source

Overview

Normalize a path, PIL image, numpy array, torch tensor, or sequence to RGB PIL. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: Image.Image.

Parameters

image_input
first_sequence_itembool
default: True

Returns: Image.Image

def materialize_image_input(image_input,output_dir: str | os.PathLike[str],filename: str = 'input.png') -> str
worldfoundry.core.materialize_image_inputfrom worldfoundry.core import materialize_image_input
source

Overview

Normalize an image-like input and save it at a stable local path. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: str.

Parameters

image_input
output_dirstr | os.PathLike[str]
filenamestr
default: 'input.png'

Returns: str

def mean_flat(tensor: torch.Tensor) -> torch.Tensor
worldfoundry.core.mean_flatfrom worldfoundry.core import mean_flat
source

Overview

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.core.normalize_action_valuesfrom worldfoundry.core import normalize_action_values
source

Overview

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
statisticsMapping[str, Any]
modestr
default: 'min_max'
clipfloat | None
default: None

Returns: np.ndarray

def normalize_registry_key(value: str, , field_name: str = 'registry key') -> str
worldfoundry.core.normalize_registry_keyfrom worldfoundry.core import normalize_registry_key
source

Overview

Normalize a user-facing registry key for case-insensitive lookup. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: str.

Parameters

valuestr
field_namestr
default: 'registry key'

Returns: str

class PostprocessingGuardrail(Protocol)
worldfoundry.core.safety.PostprocessingGuardrailfrom worldfoundry.core.safety import PostprocessingGuardrail
source

Overview

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

Methods

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

Overview

Return safety-processed frames.

Parameters

framesnp.ndarray

Returns: np.ndarray

class RegistryError()
worldfoundry.core.RegistryErrorfrom worldfoundry.core import RegistryError
source

Overview

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.core.RegistryItemfrom worldfoundry.core import RegistryItem
source

Overview

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 select_modality_statistics(dataset_statistics: Mapping[str, Any],modality: str = 'action',key: str | None = None) -> tuple[str | None, Mapping[str, Any]]
worldfoundry.core.select_modality_statisticsfrom worldfoundry.core import select_modality_statistics
source

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]
modalitystr
default: 'action'
keystr | None
default: None

Returns: tuple[str | None, Mapping[str, Any]]

def set_random_seed(seed: int, by_rank: bool = False) -> int
worldfoundry.core.set_random_seedfrom worldfoundry.core import set_random_seed
source

Overview

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

Parameters

seedint
by_rankbool
default: False

Returns: int

def split_horizontal_views(image,num_views: int,target_size: tuple[int, int] | None = None) -> list[Image.Image]
worldfoundry.core.split_horizontal_viewsfrom worldfoundry.core import split_horizontal_views
source

Overview

Split a horizontally concatenated image into equally sized RGB views. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: list[Image.Image].

Parameters

image
num_viewsint
target_sizetuple[int, int] | None
default: None

Returns: list[Image.Image]

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

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 | None
default: None

Returns: Tensor

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

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

Overview

Register an item and return the normalized registry record.

Parameters

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

Returns: RegistryItem[ItemT]

methget(key: str) -> ItemTsource

Overview

Resolve a key or alias to the registered value.

Parameters

keystr

Returns: ItemT

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

Overview

Resolve a key or alias to the full registry item.

Parameters

keystr

Returns: RegistryItem[ItemT]

methkeys() -> tuple[str, ]source

Overview

Return canonical keys in deterministic order.

Returns: tuple[str, ...]

methaliases() -> Mapping[str, str]source

Overview

Return normalized alias to normalized canonical key mapping.

Returns: Mapping[str, str]

methitems() -> tuple[RegistryItem[ItemT], ]source

Overview

Return registry items sorted by their public key.

Returns: tuple[RegistryItem[ItemT], ...]

methvalues() -> tuple[ItemT, ]source

Overview

Return registered values sorted by public key.

Returns: tuple[ItemT, ...]

class UnknownRegistryKeyError()
worldfoundry.core.UnknownRegistryKeyErrorfrom worldfoundry.core import UnknownRegistryKeyError
source

Overview

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.core.unnormalize_action_valuesfrom worldfoundry.core import unnormalize_action_values
source

Overview

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

Parameters

normalized_valuesAny
statisticsMapping[str, Any]
modestr
default: 'min_max'

Returns: np.ndarray