Core foundations
Typed registries, normalization helpers, deterministic utilities, image composition, and reusable safety guardrail protocols.
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
as_list
funcdef as_list(value, , none_as_empty: bool = True) -> listworldfoundry.core.as_listfrom worldfoundry.core import as_listOverview
Normalize optional scalar or sequence values into a plain list. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: list.
Parameters
valuenone_as_emptybool- default:
True
Returns: list
def clear_inference_runtime_cache(cache: MutableMapping[Any, Any]) -> Noneworldfoundry.core.clear_inference_runtime_cachefrom worldfoundry.core import clear_inference_runtime_cacheOverview
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.Imageworldfoundry.core.compose_horizontal_viewsfrom worldfoundry.core import compose_horizontal_viewsOverview
Resize optional per-view images and concatenate them horizontally. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: Image.Image.
Parameters
imagestarget_sizetuple[int, int] | None- default:
None
Returns: Image.Image
class ContentSafetyGuardrail(Protocol)worldfoundry.core.safety.ContentSafetyGuardrailfrom worldfoundry.core.safety import ContentSafetyGuardrailOverview
Interface implemented by prompt and media safety classifiers. Belongs to Core foundations (registries, utilities, safety contracts).
Methods
Overview
Return whether `input` is safe and an optional explanation.
Parameters
inputAny
Returns: tuple[bool, str]
divide
funcdef divide(numerator: int, denominator: int) -> intworldfoundry.core.dividefrom worldfoundry.core import divideOverview
Return exact integer division and reject a non-divisible numerator. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: int.
Parameters
numeratorintdenominatorint
Raises
AssertionError- `
numeratoris not divisible bydenominator`.
Returns: int
class DuplicateRegistryKeyError()worldfoundry.core.DuplicateRegistryKeyErrorfrom worldfoundry.core import DuplicateRegistryKeyErrorOverview
Raised when a key or alias maps to multiple different entries. Belongs to Core foundations (registries, utilities, safety contracts).
env_is_true
funcdef env_is_true(env_name: str) -> boolworldfoundry.core.env_is_truefrom worldfoundry.core import env_is_trueOverview
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 GuardrailRunnerOverview
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
Overview
Run classifiers in order and return the first block or final safe result.
Parameters
inputAny
Returns: tuple[bool, str]
Overview
Apply every configured safety postprocessor to a frame array.
Parameters
framesnp.ndarray
Returns: np.ndarray
load_pil_image
funcdef load_pil_image(image_input, , first_sequence_item: bool = True) -> Image.Imageworldfoundry.core.load_pil_imagefrom worldfoundry.core import load_pil_imageOverview
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_inputfirst_sequence_itembool- default:
True
Returns: Image.Image
def materialize_image_input(image_input,output_dir: str | os.PathLike[str],filename: str = 'input.png') -> strworldfoundry.core.materialize_image_inputfrom worldfoundry.core import materialize_image_inputOverview
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_inputoutput_dirstr | os.PathLike[str]filenamestr- default:
'input.png'
Returns: str
def normalize_action_values(values: Any,statistics: Mapping[str, Any],mode: str = 'min_max',clip: float | None = None) -> np.ndarrayworldfoundry.core.normalize_action_valuesfrom worldfoundry.core import normalize_action_valuesOverview
Normalize action values using checkpoint statistics along the last axis. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: np.ndarray.
Parameters
valuesAnystatisticsMapping[str, Any]modestr- default:
'min_max' clipfloat | None- default:
None
Returns: np.ndarray
def normalize_registry_key(value: str, , field_name: str = 'registry key') -> strworldfoundry.core.normalize_registry_keyfrom worldfoundry.core import normalize_registry_keyOverview
Normalize a user-facing registry key for case-insensitive lookup. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: str.
Parameters
valuestrfield_namestr- default:
'registry key'
Returns: str
class PostprocessingGuardrail(Protocol)worldfoundry.core.safety.PostprocessingGuardrailfrom worldfoundry.core.safety import PostprocessingGuardrailOverview
Interface implemented by safety postprocessors such as face blurring. Belongs to Core foundations (registries, utilities, safety contracts).
Methods
Overview
Return safety-processed frames.
Parameters
framesnp.ndarray
Returns: np.ndarray
class RegistryError()worldfoundry.core.RegistryErrorfrom worldfoundry.core import RegistryErrorOverview
Base class for registry definition errors. Belongs to Core foundations (registries, utilities, safety contracts).
RegistryItem
clsclass RegistryItem(key: str,value: ItemT,aliases: tuple[str, ...] = (),metadata: Mapping[str, object] = <dict factory>)worldfoundry.core.RegistryItemfrom worldfoundry.core import RegistryItemOverview
One registered item plus its public aliases. Belongs to Core foundations (registries, utilities, safety contracts).
Attributes
keystrvalueItemTaliasestuple[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_statisticsOverview
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]]
set_random_seed
funcdef set_random_seed(seed: int, by_rank: bool = False) -> intworldfoundry.core.set_random_seedfrom worldfoundry.core import set_random_seedOverview
Set Python, NumPy, and PyTorch seeds with optional distributed-rank offset. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: int.
Parameters
seedintby_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_viewsOverview
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
imagenum_viewsinttarget_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) -> Tensorworldfoundry.core.stack_or_pad_tensorsfrom worldfoundry.core import stack_or_pad_tensorsOverview
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 TypedRegistryOverview
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
register(key: str,value: ItemT,aliases: Iterable[str] = (),metadata: Mapping[str, object] | None = None) -> RegistryItem[ItemT]sourceOverview
Register an item and return the normalized registry record.
Parameters
keystrvalueItemTaliasesIterable[str]- default:
() metadataMapping[str, object] | None- default:
None
Returns: RegistryItem[ItemT]
Overview
Resolve a key or alias to the registered value.
Parameters
keystr
Returns: ItemT
Overview
Resolve a key or alias to the full registry item.
Parameters
keystr
Returns: RegistryItem[ItemT]
Overview
Return canonical keys in deterministic order.
Returns: tuple[str, ...]
Overview
Return normalized alias to normalized canonical key mapping.
Returns: Mapping[str, str]
Overview
Return registry items sorted by their public key.
Returns: tuple[RegistryItem[ItemT], ...]
Overview
Return registered values sorted by public key.
Returns: tuple[ItemT, ...]
class UnknownRegistryKeyError()worldfoundry.core.UnknownRegistryKeyErrorfrom worldfoundry.core import UnknownRegistryKeyErrorOverview
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.ndarrayworldfoundry.core.unnormalize_action_valuesfrom worldfoundry.core import unnormalize_action_valuesOverview
Convert normalized policy outputs back to environment-space actions. Belongs to Core foundations (registries, utilities, safety contracts). Annotated return type: np.ndarray.
Parameters
normalized_valuesAnystatisticsMapping[str, Any]modestr- default:
'min_max'
Returns: np.ndarray