Core inference runtime

Model inference specs, task/variant contracts, process-wide policy, autocast, compilation, torchrun commands, devices, and timers.

On this page

Core runtime makes a model's runnable surface explicit before loading its implementation. ModelInferenceSpec describes model-family identity, variants, checkpoints, task profiles, fields, artifacts, streaming support, and supported call parameters. The process helpers then apply shared execution policy without embedding one model's behavior in Core.

Build or retrieve an inference spec

from worldfoundry.core import model_inference_spec

spec = model_inference_spec(
    model_family_id="my-world-model",
    display_name="My World Model",
    default_model_ref="org/my-world-model",
    workload_type="video",
    supported_call_params=("prompt", "seed", "num_frames"),
)

assert spec.model_family_id == "my-world-model"
assert spec.variant().variant_id == "default"
assert spec.task().task_id

For a curated built-in family, model_inference_spec returns the registered spec. For an unknown family it builds a generic spec from the supplied hints. Use get_model_inference_spec when “not registered” must remain distinguishable from a fallback.

Process-wide inference policy

install_worldfoundry_inference_infra configures attention policy, float32 matmul precision, TF32 flags, and an optional SDPA compatibility patch. It is idempotent process state, not a per-request object. worldfoundry_inference_context installs that state and runs under torch.no_grad().

autocast_context returns a CUDA autocast manager only for CUDA devices; CPU and unavailable-Torch cases return a no-op context. compile_module_if_enabled is explicitly opt-in and returns the original module if compilation is disabled, unsupported, or fails in non-strict mode.

from torch import nn
from worldfoundry.core import compile_module_if_enabled, torchrun_module_command

module = nn.Linear(4, 2)
assert compile_module_if_enabled(module, enabled=False) is module

command = torchrun_module_command(
    "my_package.worker",
    nproc_per_node=4,
    args=("--checkpoint", "/models/run-42"),
)
print(command)  # builds the command; it does not start a process

Use run_torchrun_module only when the current process should own launching and capturing a bounded single-node job. It returns CompletedProcess even on a non-zero child exit, so callers must inspect returncode and logs.

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.

40 public symbols

def adaptive_batched_inference(inputs: torch.Tensor,forward: Callable[[torch.Tensor], torch.Tensor],batch_size: int,device: torch.device | str | int | None = None,output_device: torch.device | str | int | None = None,minimum_batch_size: int = 1,batch_size_buckets: Sequence[int] | None = None,pad_to_batch_size: bool = False,scope: str | None = None,compile_forward: bool | None = None,compile_mode: str | None = None,persistent_forward: bool = False) -> torch.Tensor
worldfoundry.corefrom worldfoundry.core import adaptive_batched_inference

Overview

Run tensor inference in bounded, optionally shape-stable batches. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: torch.Tensor.

Source docstring

Run tensor inference in bounded, optionally shape-stable batches.

Only the failed slice is retried. Successful outputs retain input order, and an allocation failure at batch size one is propagated unchanged. `pad_to_batch_size repeats the final real item and trims its outputs; this is intended for independent per-item encoders so Inductor and CUDA Graphs can reuse a small set of static leading dimensions. persistent_forward` declares that a closure is reused across multiple calls, allowing throughput mode to retain one compiled wrapper. It does not enable compilation by itself.

Parameters

inputstorch.Tensor
forwardCallable[[torch.Tensor], torch.Tensor]
batch_sizeint
devicetorch.device | str | int | Nonedefault None
output_devicetorch.device | str | int | Nonedefault None
minimum_batch_sizeintdefault 1
batch_size_bucketsSequence[int] | Nonedefault None
pad_to_batch_sizebooldefault False
scopestr | Nonedefault None
compile_forwardbool | Nonedefault None
compile_modestr | Nonedefault None
persistent_forwardbooldefault False

Returns

torch.Tensor
def autocast_context(device: Any,dtype: Any | None = None,enabled: bool = True) -> Any
worldfoundry.corefrom worldfoundry.core import autocast_context

Overview

Return a CUDA autocast context and a no-op context for non-CUDA devices. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: Any.

Source docstring

Return a CUDA autocast context and a no-op context for non-CUDA devices.

*device* may be a tensor, `torch.device, or device string. CPU / NPU / missing-torch paths return :func:contextlib.nullcontext`.

Parameters

deviceAny
dtypeAny | Nonedefault None
enabledbooldefault True

Returns

Any
def bind_log_context(**fields: Any) -> Token[dict[str, Any]]
worldfoundry.corefrom worldfoundry.core import bind_log_context

Overview

Bind correlation fields for the current execution context. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: Token[dict[str, Any]].

Source docstring

Bind correlation fields for the current execution context.

The returned token can be passed to :meth:contextvars.ContextVar.reset, or callers can prefer :func:log_context for scoped use.

Parameters

fieldsAny

Returns

Token[dict[str, Any]]
def clear_inference_runtime_cache(cache: MutableMapping[Any, Any]) -> None
worldfoundry.corefrom worldfoundry.core import clear_inference_runtime_cache

Overview

Drop cached runtimes and release unreferenced accelerator allocations. Belongs to Core inference runtime (process setup, compile, timers, realtime). 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 clear_log_context() -> None
worldfoundry.corefrom worldfoundry.core import clear_log_context

Clear all correlation fields for the current execution context. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: None.

Returns

None
def compile_module_if_enabled(module: Any,enabled: bool | None = None,label: str | None = None,backend: str | None = None,mode: str | None = None,fullgraph: bool | None = None,dynamic: bool | None = None,options: dict[str, Any] | None = None) -> Any
worldfoundry.corefrom worldfoundry.core import compile_module_if_enabled

Overview

Compile one module with persistent cache and wrapper reuse when enabled. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: Any.

Source docstring

Compile one module with persistent cache and wrapper reuse when enabled.

Honours `WORLDFOUNDRY_TORCH_COMPILE and the matching _BACKEND / _MODE / _FULLGRAPH / _DYNAMIC / _STRICT env vars when the explicit kwargs are omitted. Already compiled wrappers (_worldfoundry_core_compiled) are returned unchanged. Delegates to :func:worldfoundry.core.execution.compile_cache.compile_module_cached`.

Parameters

moduleAny
enabledbool | Nonedefault None
labelstr | Nonedefault None
backendstr | Nonedefault None
modestr | Nonedefault None
fullgraphbool | Nonedefault None
dynamicbool | Nonedefault None
optionsdict[str, Any] | Nonedefault None

Returns

Any
def configure_logging(level: str | int | None = None,log_file: str | os.PathLike | None = None,json: bool | None = None,rotation: str = '10 MB',retention: str = '1 week',colorize: bool | None = None,force: bool = False) -> None
worldfoundry.corefrom worldfoundry.core import configure_logging

Overview

Configure WorldFoundry's unified logging pipeline. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: None.

Source docstring

Configure WorldFoundry's unified logging pipeline.

Idempotent: a second call without `force=True` is a no-op, so it is safe to invoke from every framework entry point (CLI, model-runtime worker, …) without duplicating handlers/sinks.

Parameters

levelstr | int | Nonedefault None
Threshold for *every* log source. Accepts a name (`"DEBUG"/"INFO"/…, case-insensitive; "WARN"/"TRACE" accepted as aliases) or an int level. None falls back to the WORLDFOUNDRY_LOG_LEVEL` env var, then INFO.
log_filestr | os.PathLike | Nonedefault None
Optional rotating file sink. `None falls back to the WORLDFOUNDRY_LOG_FILE` env var, else no file sink.
jsonbool | Nonedefault None
When true the file sink emits JSON Lines (the console stays colored text). `None falls back to WORLDFOUNDRY_LOG_JSON`.
rotationstrdefault '10 MB'
Size threshold for file rotation (e.g. `"10 MB"`).
retentionstrdefault '1 week'
How many rotated files to keep (e.g. `"1 week"` → 7 backups; only the count is honoured by the stdlib path).
colorizebool | Nonedefault None
Override console colorization (loguru path only).
forcebooldefault False
Reconfigure even if already configured.

Returns

None
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 inference runtime (process setup, compile, timers, realtime). 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
class CudaSyncTimer(name: str | None = None,flag_env: str = 'SYNC_TIMER',log_fn: Callable[[str], None] | None = None)
worldfoundry.corefrom worldfoundry.core import CudaSyncTimer

Overview

Optional CUDA-synchronized timer usable as a context manager or decorator. Belongs to Core inference runtime (process setup, compile, timers, realtime).

Source docstring

Optional CUDA-synchronized timer usable as a context manager or decorator.

Construction is cheap and has no torch dependency. `__enter__ reads *flag_env* (default SYNC_TIMER) and no-ops unless it is "1". When enabled it records elapsed_ms and, if *name* is set, logs "{name} takes X.XXXXs"`.

As a decorator, each call wraps the function in `with self:`.

Parameters

namestr | Nonedefault None
flag_envstrdefault 'SYNC_TIMER'
log_fnCallable[[str], None] | Nonedefault None

Methods

meth__call__(func)Source

Wrap *func* so each call is timed with this same timer instance.

Parameters

func
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 inference runtime (process setup, compile, timers, realtime). 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
def get_log_context() -> dict[str, Any]
worldfoundry.corefrom worldfoundry.core import get_log_context

Return a copy of the current correlation fields. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: dict[str, Any].

Returns

dict[str, Any]
def get_logger(name: str | None = None) -> WorldFoundryLoggerAdapter
worldfoundry.corefrom worldfoundry.core import get_logger

Overview

Return the WorldFoundry structured-event facade for a stdlib logger. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: WorldFoundryLoggerAdapter.

Parameters

namestr | Nonedefault None

Returns

WorldFoundryLoggerAdapter
worldfoundry.corefrom worldfoundry.core import inference_infra_state

Overview

Return the process-global inference infra state (do not mutate casually). Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: WorldFoundryInferenceInfraState.

Source docstring

Return the process-global inference infra state (do not mutate casually).

The returned dataclass is the live singleton updated by :func:install_worldfoundry_inference_infra and :func:uninstall_worldfoundry_inference_infra.

class InferenceArtifactSpec(artifact_id: str,kind: str,required: bool = False,preview: bool = False,description: str = '')
worldfoundry.corefrom worldfoundry.core import InferenceArtifactSpec

Output artifact contract emitted by an inference task profile. Belongs to Core inference runtime (process setup, compile, timers, realtime).

Attributes

artifact_idstr
kindstr
requiredbooldefault False
previewbooldefault False
descriptionstrdefault ''

Methods

methto_dict() -> dict[str, Any]Source

Serialize this artifact contract to a JSON-ready mapping.

Returns

dict[str, Any]
class InferenceCheckpointRef(role: str,uri: str,required: bool = True,status: str = 'unknown')
worldfoundry.corefrom worldfoundry.core import InferenceCheckpointRef

Checkpoint reference used by a concrete inference variant. Belongs to Core inference runtime (process setup, compile, timers, realtime).

Attributes

rolestr
uristr
requiredbooldefault True
statusstrdefault 'unknown'

Methods

methto_dict() -> dict[str, Any]Source

Serialize this checkpoint reference (role, URI, required, status).

Returns

dict[str, Any]
class InferenceFieldSpec(field_id: str,label: str,kind: str = 'string',target: str = 'call_kwargs',required: bool = False,default: Any = None,choices: tuple[str, ...] = (),description: str = '')
worldfoundry.corefrom worldfoundry.core import InferenceFieldSpec

User-facing input field contract for one inference task profile. Belongs to Core inference runtime (process setup, compile, timers, realtime).

Attributes

field_idstr
labelstr
kindstrdefault 'string'
targetstrdefault 'call_kwargs'
requiredbooldefault False
defaultAnydefault None
choicestuple[str, ...]default ()
descriptionstrdefault ''

Methods

methto_dict() -> dict[str, Any]Source

Serialize this field contract to a JSON-ready mapping.

Returns

dict[str, Any]
class InferenceTaskProfile(task_id: str,label: str,inputs: tuple[InferenceFieldSpec, ...],outputs: tuple[InferenceArtifactSpec, ...],description: str = '',default_call_kwargs: Mapping[str, Any] = <dict factory>,aliases: tuple[str, ...] = ())
worldfoundry.corefrom worldfoundry.core import InferenceTaskProfile

Runnable inference task profile for a model family or variant. Belongs to Core inference runtime (process setup, compile, timers, realtime).

Attributes

task_idstr
labelstr
inputstuple[InferenceFieldSpec, ...]
outputstuple[InferenceArtifactSpec, ...]
descriptionstrdefault ''
default_call_kwargsMapping[str, Any]default <dict factory>
aliasestuple[str, ...]default ()

Methods

methto_dict() -> dict[str, Any]Source

Serialize this task profile, including nested field/artifact specs.

Returns

dict[str, Any]
class InferenceVariantSpec(variant_id: str,label: str,checkpoints: tuple[InferenceCheckpointRef, ...] = (),status: str = 'unknown',load_kwargs: Mapping[str, Any] = <dict factory>,call_kwargs: Mapping[str, Any] = <dict factory>,aliases: tuple[str, ...] = (),notes: tuple[str, ...] = ())
worldfoundry.corefrom worldfoundry.core import InferenceVariantSpec

Concrete checkpoint/runtime variant under a model family. Belongs to Core inference runtime (process setup, compile, timers, realtime).

Attributes

variant_idstr
labelstr
checkpointstuple[InferenceCheckpointRef, ...]default ()
statusstrdefault 'unknown'
load_kwargsMapping[str, Any]default <dict factory>
call_kwargsMapping[str, Any]default <dict factory>
aliasestuple[str, ...]default ()
notestuple[str, ...]default ()

Methods

propprimary_checkpoint_uri -> strSource

URI of the `primary / base / checkpoint` role, else the first.

Parameters

self

Returns

str
methcheckpoint_map() -> dict[str, str]Source

Map each checkpoint role onto its URI.

Returns

dict[str, str]
methto_dict() -> dict[str, Any]Source

Serialize this variant, including `model_ref` and checkpoint map.

Returns

dict[str, Any]
def install_worldfoundry_inference_infra(attention_backend: str | None = None,matmul_precision: str | None = None,enable_tf32: bool | None = None,patch_sdpa: bool | None = None) -> WorldFoundryInferenceInfraState
worldfoundry.corefrom worldfoundry.core import install_worldfoundry_inference_infra

Overview

Install WorldFoundry core inference optimizations for this process. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: WorldFoundryInferenceInfraState.

Source docstring

Install WorldFoundry core inference optimizations for this process.

Environment controls: - `WORLDFOUNDRY_USE_CORE_INFRA=0 disables installation. - WORLDFOUNDRY_ATTENTION_BACKEND=auto|flash|cudnn|efficient|math selects the SDPA backend policy. Attention dispatch backend names (for example flash_attention_2, sage_attention, xformers) are also accepted; they resolve the SDPA policy to auto and are honoured by worldfoundry.core.attention instead. - WORLDFOUNDRY_MATMUL_PRECISION=highest|high|medium selects PyTorch float32 matmul precision. - WORLDFOUNDRY_ENABLE_TF32=0 disables TF32 backend flags. - WORLDFOUNDRY_PATCH_SDPA=0 avoids monkey-patching PyTorch SDPA calls. - WORLDFOUNDRY_DETERMINISTIC=1 enables torch.use_deterministic_algorithms` and CuDNN deterministic mode (XC-23).

Use :func:uninstall_worldfoundry_inference_infra (or the :func:worldfoundry_inference_infra_disabled context manager) to restore the original SDPA function and pre-install torch backend flags.

Parameters

attention_backendstr | Nonedefault None
matmul_precisionstr | Nonedefault None
enable_tf32bool | Nonedefault None
patch_sdpabool | Nonedefault None
def is_accelerator_out_of_memory(exc: BaseException) -> bool
worldfoundry.corefrom worldfoundry.core import is_accelerator_out_of_memory

Return whether an exception reports an accelerator allocation failure. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: bool.

Parameters

excBaseException

Returns

bool
def log_context(**fields: Any) -> Iterator[None]
worldfoundry.corefrom worldfoundry.core import log_context

Temporarily bind correlation fields for a block of work. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: Iterator[None].

Parameters

fieldsAny

Returns

Iterator[None]
def log_context_environment(**fields: Any) -> dict[str, str]
worldfoundry.corefrom worldfoundry.core import log_context_environment

Overview

Serialize current correlation fields for a framework-owned child process. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: dict[str, str].

Source docstring

Serialize current correlation fields for a framework-owned child process.

This deliberately carries only structured context, never logger handlers or raw stdout/stderr. It is safe to merge into a child `env` mapping.

Parameters

fieldsAny

Returns

dict[str, str]
class ModelInferenceSpec(model_family_id: str,display_name: str,variants: tuple[InferenceVariantSpec, ...],tasks: tuple[InferenceTaskProfile, ...],default_variant_id: str = 'default',default_task_id: str = 'default',aliases: tuple[str, ...] = (),notes: tuple[str, ...] = ())
worldfoundry.corefrom worldfoundry.core import ModelInferenceSpec

Inference contract shared by Studio, CLI, manifests, and eval. Belongs to Core inference runtime (process setup, compile, timers, realtime).

Attributes

model_family_idstr
display_namestr
variantstuple[InferenceVariantSpec, ...]
taskstuple[InferenceTaskProfile, ...]
default_variant_idstrdefault 'default'
default_task_idstrdefault 'default'
aliasestuple[str, ...]default ()
notestuple[str, ...]default ()

Methods

methvariant(variant_id: str | None = None) -> InferenceVariantSpecSource

Look up a variant by id or alias; default is `default_variant_id`.

Parameters

variant_idstr | Nonedefault None

Raises

ValueError
No variant matches the (normalized) identifier.
methtask(task_id: str | None = None) -> InferenceTaskProfileSource

Look up a task profile by id or alias; default is `default_task_id`.

Parameters

task_idstr | Nonedefault None

Raises

ValueError
No task matches the (normalized) identifier.
methto_dict() -> dict[str, Any]Source

Serialize the family contract, including nested variants and tasks.

Returns

dict[str, Any]
def profile_torch_module(model: Any,inputs: Any = (),model_id: str | None = None,input_spec: Mapping[str, Any] | None = None,event_log_path: str | Path | None = None,set_eval: bool = True,strict: bool = False) -> TorchProfileResult
worldfoundry.corefrom worldfoundry.core import profile_torch_module

Overview

Trace *model* with TorchProfile and log a static compute summary. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: TorchProfileResult.

Parameters

modelAny
A loaded PyTorch module. The caller retains ownership of the model and its device placement.
inputsAnydefault ()
One tensor or tuple of positional tensors representative of the inference workload. `torchprofile` does not support keyword-argument tracing.
model_idstr | Nonedefault None
Optional model identifier; promoted to a top-level field in WorldFoundry JSON logs.
input_specMapping[str, Any] | Nonedefault None
Optional JSON-safe shape/dtype metadata for the event. Do not place actual tensor values or credentials in this mapping.
event_log_pathstr | Path | Nonedefault None
Optional run-owned JSONL path that receives the same canonical structured event even when no logger sink is configured.
set_evalbooldefault True
Temporarily call `model.eval()` for deterministic tracing and restore all module training flags afterwards.
strictbooldefault False
Re-raise unavailable/profile failures after emitting the event.

Returns

TorchProfileResultA :class:TorchProfileResult. With `strict=False` (the default), missing optional dependencies and trace incompatibilities are reported as result statuses rather than breaking the underlying model run.
def read_text_tail(path: str | Path,max_lines: int = 20,max_bytes: int = 64 * 1024) -> str
worldfoundry.corefrom worldfoundry.core import read_text_tail

Overview

Read a bounded UTF-8 tail from a potentially very large log file. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: str.

Source docstring

Read a bounded UTF-8 tail from a potentially very large log file.

Seeks to `max(size - max_bytes, 0) and keeps the last *max_lines* decoded lines. A mid-file seek drops the first partial line so the result does not start with a torn UTF-8 sequence. Missing files yield ""`.

Parameters

pathstr | Path
max_linesintdefault 20
max_bytesintdefault 64 * 1024

Returns

str
class RealtimeSpec(fps: int = 16,first_chunk_frames: int = 9,steady_chunk_frames: int = 9,controls: tuple[str, ...] = DEFAULT_REALTIME_CONTROLS,transport: str = 'in-memory-rgb',stateful: bool = True,input_fps: float | None = None,first_input_frames: int | None = None,steady_input_frames: int | None = None)
worldfoundry.core.execution.realtime.contractsfrom worldfoundry.core.execution.realtime.contracts import RealtimeSpec

Model-owned playback and generation cadence for one resident session. Belongs to Core inference runtime (process setup, compile, timers, realtime).

Attributes

fpsintdefault 16
first_chunk_framesintdefault 9
steady_chunk_framesintdefault 9
controlstuple[str, ...]default DEFAULT_REALTIME_CONTROLS
transportstrdefault 'in-memory-rgb'
statefulbooldefault True
input_fpsfloat | Nonedefault None
first_input_framesint | Nonedefault None
steady_input_framesint | Nonedefault None

Methods

propresolved_input_fps -> floatSource

Control/input sampling FPS, defaulting to the playback clock.

Parameters

self

Returns

float
propresolved_first_input_frames -> intSource

First control chunk size, defaulting to first output frames.

Parameters

self

Returns

int
propresolved_steady_input_frames -> intSource

Steady control chunk size, defaulting to steady output frames.

Parameters

self

Returns

int
methto_payload() -> dict[str, Any]Source

JSON-safe dict; omit unset optional input-clock fields so clients do not treat `null` as 0.

Returns

dict[str, Any]
cmethfrom_payload(value: Any,fallback: 'RealtimeSpec | None' = None) -> 'RealtimeSpec'Source

Parse a model result without letting malformed metadata break play.

Parameters

valueAny
fallback'RealtimeSpec | None'default None

Returns

def resolve_inference_batch_size(default_batch_size: int,device: torch.device | str | int | None = None,scope: str | None = None,minimum: int = 1,maximum: int | None = None,reference_free_memory_gib: float = 24.0) -> int
worldfoundry.corefrom worldfoundry.core import resolve_inference_batch_size

Overview

Choose a capability-neutral inference batch size from free device memory. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: int.

Source docstring

Choose a capability-neutral inference batch size from free device memory.

The default is treated as the batch size for roughly 24 GiB of free memory. Smaller devices start conservatively, while 80 GiB and newer high-memory accelerators can use larger batches. Scoped and global environment values take precedence over automatic sizing.

Parameters

default_batch_sizeint
devicetorch.device | str | int | Nonedefault None
scopestr | Nonedefault None
minimumintdefault 1
maximumint | Nonedefault None
reference_free_memory_gibfloatdefault 24.0

Returns

int
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 inference runtime (process setup, compile, timers, realtime). 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 inference runtime (process setup, compile, timers, realtime). 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 run_logged_subprocess(command: str | Sequence[str],stdout_path: str | Path,stderr_path: str | Path,cwd: str | Path | None = None,env: Mapping[str, str] | None = None,timeout: float | None = None,shell: bool = False,append: bool = False,start_new_session: bool | None = None) -> subprocess.CompletedProcess[Any]
worldfoundry.corefrom worldfoundry.core import run_logged_subprocess

Overview

Run a subprocess with bounded log memory and timeout-safe descendants. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: subprocess.CompletedProcess[Any].

Source docstring

Run a subprocess with bounded log memory and timeout-safe descendants.

The child receives the current WorldFoundry correlation context and gets a dedicated JSONL lifecycle artifact beside its raw stdout/stderr captures. This keeps framework-owned workers observable without requiring changes to vendored official benchmark code.

Parameters

commandstr | Sequence[str]
stdout_pathstr | Path
stderr_pathstr | Path
cwdstr | Path | Nonedefault None
envMapping[str, str] | Nonedefault None
timeoutfloat | Nonedefault None
shellbooldefault False
appendbooldefault False
start_new_sessionbool | Nonedefault None

Returns

subprocess.CompletedProcess[Any]
def run_torchrun_module(module: str,nproc_per_node: int,args: Sequence[str] = (),env: Mapping[str, str] | None = None,python_executable: str = sys.executable) -> subprocess.CompletedProcess[str]
worldfoundry.corefrom worldfoundry.core import run_torchrun_module

Overview

Run a single-node Python module under torchrun and capture its logs. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: subprocess.CompletedProcess[str].

Source docstring

Run a single-node Python module under torchrun and capture its logs.

Uses :func:subprocess.run with `capture_output=True and check=False. Prefer :func:run_logged_subprocess` when the worker may run long enough that in-memory capture is unsafe.

Parameters

modulestr
nproc_per_nodeint
argsSequence[str]default ()
envMapping[str, str] | Nonedefault None
python_executablestrdefault sys.executable

Returns

subprocess.CompletedProcess[str]
def terminate_process_group(process: subprocess.Popen[Any],grace_seconds: float = 3.0) -> None
worldfoundry.corefrom worldfoundry.core import terminate_process_group

Overview

Terminate a process and all descendants in its dedicated process group. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: None.

Source docstring

Terminate a process and all descendants in its dedicated process group.

POSIX path sends `SIGTERM to the group (os.killpg), waits *grace_seconds*, then SIGKILL. Windows falls back to terminate / kill on the parent only. Already-exited groups are a no-op. The child must have been started with start_new_session=True (see :func:run_logged_subprocess`).

Parameters

processsubprocess.Popen[Any]
grace_secondsfloatdefault 3.0

Returns

None
def terminate_process_tree(process: subprocess.Popen[Any],grace_seconds: float = 3.0) -> None
worldfoundry.corefrom worldfoundry.core import terminate_process_tree

Overview

Terminate one process and recursively terminate descendants without a process group. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: None.

Source docstring

Terminate one process and recursively terminate descendants without a process group.

Used when the child was *not* started in a new session. With `psutil installed, children are terminate'd first, then the parent, then any survivors are kill`'d. Without psutil only the parent is signalled — grandchildren may leak.

Parameters

processsubprocess.Popen[Any]
grace_secondsfloatdefault 3.0

Returns

None
class TorchProfileResult(status: Literal['completed', 'unavailable', 'failed'],macs: int | None = None,flops_estimate: int | None = None,parameter_count: int | None = None,torchprofile_version: str | None = None,model_class: str | None = None,error: str | None = None)
worldfoundry.corefrom worldfoundry.core import TorchProfileResult

A compact static-compute result from one optional TorchProfile trace. Belongs to Core inference runtime (process setup, compile, timers, realtime).

Attributes

statusLiteral['completed', 'unavailable', 'failed']
macsint | Nonedefault None
flops_estimateint | Nonedefault None
parameter_countint | Nonedefault None
torchprofile_versionstr | Nonedefault None
model_classstr | Nonedefault None
errorstr | Nonedefault None

Methods

methto_dict() -> dict[str, Any]Source

Return a JSON-compatible representation suitable for result payloads.

Returns

dict[str, Any]
def torchrun_module_command(module: str,nproc_per_node: int,args: Sequence[str] = (),python_executable: str = sys.executable) -> list[str]
worldfoundry.corefrom worldfoundry.core import torchrun_module_command

Overview

Build a single-node torchrun command for a Python module. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: list[str].

Source docstring

Build a single-node torchrun command for a Python module.

Equivalent to `python -m torch.distributed.run --standalone --nproc_per_node N -m MODULE ...`. Does not launch the process.

Parameters

modulestr
nproc_per_nodeint
argsSequence[str]default ()
python_executablestrdefault sys.executable

Returns

list[str]
def utc_now_iso() -> str
worldfoundry.corefrom worldfoundry.core import utc_now_iso

Return the current UTC timestamp in ISO-8601 form with a `Z suffix. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: str`.

Returns

str
def worldfoundry_inference_context() -> Iterator[None]
worldfoundry.corefrom worldfoundry.core import worldfoundry_inference_context

Overview

Run model inference under the shared WorldFoundry core runtime policy. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: Iterator[None].

Source docstring

Run model inference under the shared WorldFoundry core runtime policy.

Installs process-wide infra if needed, then yields inside `torch.no_grad()` when torch is importable. A missing torch install still enters the context so CPU-only control planes do not crash.

Returns

Iterator[None]
class WorldFoundryInferenceInfraState(installed: bool = False,sdpa_patched: bool = False,attention_backend: str = 'auto',matmul_precision: str = 'high',tf32_enabled: bool = True)
worldfoundry.corefrom worldfoundry.core import WorldFoundryInferenceInfraState

Observable process-wide inference acceleration state. Belongs to Core inference runtime (process setup, compile, timers, realtime).

Attributes

installedbooldefault False
sdpa_patchedbooldefault False
Whether the compatibility SDPA monkey-patch is active.
attention_backendstrdefault 'auto'
Normalized attention backend policy (`auto, flash, math, …). External names such as flash_attention_2 are accepted by the installer and mapped to the SDPA policy auto`.
matmul_precisionstrdefault 'high'
Current float32 matmul precision (`highest / high / medium`).
tf32_enabledbooldefault True
Whether CUDA TF32 matmul/cudnn execution is enabled.
def wrap_runner_for_worldfoundry_core(runner: Any) -> Any
worldfoundry.corefrom worldfoundry.core import wrap_runner_for_worldfoundry_core

Overview

Wrap a runner instance so `generate always uses core inference infra. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: Any`.

Source docstring

Wrap a runner instance so `generate` always uses core inference infra.

Installs infra, then replaces `runner.generate with a wrapper that enters :func:worldfoundry_inference_context. Idempotent: a second call returns the same instance. Runners without generate` are returned unchanged.

Parameters

runnerAny

Returns

Any
def write_jsonl_event(path: str | os.PathLike[str],level: str,event: str,message: str,logger_name: str = 'worldfoundry',exception: BaseException | str | None = None,**fields: Any) -> dict[str, Any]
worldfoundry.corefrom worldfoundry.core import write_jsonl_event

Overview

Append one canonical lifecycle event to a run-owned JSONL artifact. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: dict[str, Any].

Source docstring

Append one canonical lifecycle event to a run-owned JSONL artifact.

Use this for process boundaries where a child may not import the central logger. Normal in-process application events should use :meth:WorldFoundryLoggerAdapter.event instead.

Parameters

pathstr | os.PathLike[str]
levelstr
eventstr
messagestr
logger_namestrdefault 'worldfoundry'
exceptionBaseException | str | Nonedefault None
fieldsAny

Returns

dict[str, Any]