Core inference runtime
Model inference specs, task/variant contracts, process-wide policy, autocast, compilation, torchrun commands, devices, and timers.
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_idFor 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 processUse 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
adaptive_batched_inference
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.TensorOverview
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.TensorforwardCallable[[torch.Tensor], torch.Tensor]batch_sizeintdevicetorch.device | str | int | Nonedefault Noneoutput_devicetorch.device | str | int | Nonedefault Noneminimum_batch_sizeintdefault 1batch_size_bucketsSequence[int] | Nonedefault Nonepad_to_batch_sizebooldefault Falsescopestr | Nonedefault Nonecompile_forwardbool | Nonedefault Nonecompile_modestr | Nonedefault Nonepersistent_forwardbooldefault FalseReturns
autocast_context
def autocast_context(device: Any,dtype: Any | None = None,enabled: bool = True) -> AnyOverview
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
deviceAnydtypeAny | Nonedefault Noneenabledbooldefault TrueReturns
bind_log_context
def bind_log_context(**fields: Any) -> Token[dict[str, Any]]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
fieldsAnyReturns
def clear_inference_runtime_cache(cache: MutableMapping[Any, Any]) -> NoneOverview
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
clear_log_context
def clear_log_context() -> NoneClear all correlation fields for the current execution context. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: None.
Returns
compile_module_if_enabled
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) -> AnyOverview
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
moduleAnyenabledbool | Nonedefault Nonelabelstr | Nonedefault Nonebackendstr | Nonedefault Nonemodestr | Nonedefault Nonefullgraphbool | Nonedefault Nonedynamicbool | Nonedefault Noneoptionsdict[str, Any] | Nonedefault NoneReturns
configure_logging
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) -> NoneOverview
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"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 NoneNone falls back to the WORLDFOUNDRY_LOG_FILE` env var, else no file sink.jsonbool | Nonedefault NoneNone falls back to WORLDFOUNDRY_LOG_JSON`.rotationstrdefault '10 MB'"10 MB"`).retentionstrdefault '1 week'"1 week"` → 7 backups; only the count is honoured by the stdlib path).colorizebool | Nonedefault Noneforcebooldefault FalseReturns
def cuda_visible_devices_from_device(device: str | torch.device | None,inherited: str | None = None,map_inherited: bool = True,default_cuda: str = '0') -> str | NoneOverview
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 | Noneinheritedstr | Nonedefault Nonemap_inheritedbooldefault Truedefault_cudastrdefault '0'Returns
CudaSyncTimer
class CudaSyncTimer(name: str | None = None,flag_env: str = 'SYNC_TIMER',log_fn: Callable[[str], None] | None = None)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 Noneflag_envstrdefault 'SYNC_TIMER'log_fnCallable[[str], None] | Nonedefault NoneMethods
Wrap *func* so each call is timed with this same timer instance.
Parameters
funcget_current_torch_device
def get_current_torch_device() -> torch.deviceOverview
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
get_log_context
def get_log_context() -> dict[str, Any]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
get_logger
def get_logger(name: str | None = None) -> WorldFoundryLoggerAdapterOverview
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 NoneReturns
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 = '')Output artifact contract emitted by an inference task profile. Belongs to Core inference runtime (process setup, compile, timers, realtime).
Attributes
artifact_idstrkindstrrequiredbooldefault Falsepreviewbooldefault Falsedescriptionstrdefault ''Methods
Serialize this artifact contract to a JSON-ready mapping.
Returns
class InferenceCheckpointRef(role: str,uri: str,required: bool = True,status: str = 'unknown')Checkpoint reference used by a concrete inference variant. Belongs to Core inference runtime (process setup, compile, timers, realtime).
Attributes
rolestruristrrequiredbooldefault Truestatusstrdefault 'unknown'Methods
Serialize this checkpoint reference (role, URI, required, status).
Returns
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 = '')User-facing input field contract for one inference task profile. Belongs to Core inference runtime (process setup, compile, timers, realtime).
Attributes
field_idstrlabelstrkindstrdefault 'string'targetstrdefault 'call_kwargs'requiredbooldefault FalsedefaultAnydefault Nonechoicestuple[str, ...]default ()descriptionstrdefault ''Methods
Serialize this field contract to a JSON-ready mapping.
Returns
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, ...] = ())Runnable inference task profile for a model family or variant. Belongs to Core inference runtime (process setup, compile, timers, realtime).
Attributes
task_idstrlabelstrinputstuple[InferenceFieldSpec, ...]outputstuple[InferenceArtifactSpec, ...]descriptionstrdefault ''default_call_kwargsMapping[str, Any]default <dict factory>aliasestuple[str, ...]default ()Methods
Serialize this task profile, including nested field/artifact specs.
Returns
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, ...] = ())Concrete checkpoint/runtime variant under a model family. Belongs to Core inference runtime (process setup, compile, timers, realtime).
Attributes
variant_idstrlabelstrstatusstrdefault 'unknown'load_kwargsMapping[str, Any]default <dict factory>call_kwargsMapping[str, Any]default <dict factory>aliasestuple[str, ...]default ()notestuple[str, ...]default ()Methods
URI of the `primary / base / checkpoint` role, else the first.
Parameters
selfReturns
Map each checkpoint role onto its URI.
Returns
Serialize this variant, including `model_ref` and checkpoint map.
Returns
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) -> WorldFoundryInferenceInfraStateOverview
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 Nonematmul_precisionstr | Nonedefault Noneenable_tf32bool | Nonedefault Nonepatch_sdpabool | Nonedefault Nonedef is_accelerator_out_of_memory(exc: BaseException) -> boolReturn whether an exception reports an accelerator allocation failure. Belongs to Core inference runtime (process setup, compile, timers, realtime). Annotated return type: bool.
Parameters
excBaseExceptionReturns
log_context
def log_context(**fields: Any) -> Iterator[None]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
fieldsAnyReturns
log_context_environment
def log_context_environment(**fields: Any) -> dict[str, str]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
fieldsAnyReturns
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, ...] = ())Inference contract shared by Studio, CLI, manifests, and eval. Belongs to Core inference runtime (process setup, compile, timers, realtime).
Attributes
model_family_idstrdisplay_namestrvariantstuple[InferenceVariantSpec, ...]taskstuple[InferenceTaskProfile, ...]default_variant_idstrdefault 'default'default_task_idstrdefault 'default'aliasestuple[str, ...]default ()notestuple[str, ...]default ()Methods
Look up a variant by id or alias; default is `default_variant_id`.
Parameters
variant_idstr | Nonedefault NoneReturns
Raises
ValueError- No variant matches the (normalized) identifier.
Look up a task profile by id or alias; default is `default_task_id`.
Parameters
task_idstr | Nonedefault NoneReturns
Raises
ValueError- No task matches the (normalized) identifier.
Serialize the family contract, including nested variants and tasks.
Returns
profile_torch_module
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) -> TorchProfileResultOverview
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
modelAnyinputsAnydefault ()torchprofile` does not support keyword-argument tracing.model_idstr | Nonedefault Noneinput_specMapping[str, Any] | Nonedefault Noneevent_log_pathstr | Path | Nonedefault Noneset_evalbooldefault Truemodel.eval()` for deterministic tracing and restore all module training flags afterwards.strictbooldefault FalseReturns
TorchProfileResult. With `strict=False` (the default), missing optional dependencies and trace incompatibilities are reported as result statuses rather than breaking the underlying model run.read_text_tail
def read_text_tail(path: str | Path,max_lines: int = 20,max_bytes: int = 64 * 1024) -> strOverview
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 | Pathmax_linesintdefault 20max_bytesintdefault 64 * 1024Returns
RealtimeSpec
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)Model-owned playback and generation cadence for one resident session. Belongs to Core inference runtime (process setup, compile, timers, realtime).
Attributes
fpsintdefault 16first_chunk_framesintdefault 9steady_chunk_framesintdefault 9controlstuple[str, ...]default DEFAULT_REALTIME_CONTROLStransportstrdefault 'in-memory-rgb'statefulbooldefault Trueinput_fpsfloat | Nonedefault Nonefirst_input_framesint | Nonedefault Nonesteady_input_framesint | Nonedefault NoneMethods
Control/input sampling FPS, defaulting to the playback clock.
Parameters
selfReturns
First control chunk size, defaulting to first output frames.
Parameters
selfReturns
Steady control chunk size, defaulting to steady output frames.
Parameters
selfReturns
JSON-safe dict; omit unset optional input-clock fields so clients do not treat `null` as 0.
Returns
Parse a model result without letting malformed metadata break play.
Parameters
valueAnyReturns
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) -> intOverview
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_sizeintdevicetorch.device | str | int | Nonedefault Nonescopestr | Nonedefault Noneminimumintdefault 1maximumint | Nonedefault Nonereference_free_memory_gibfloatdefault 24.0Returns
resolve_inference_device
def resolve_inference_device(device: str | torch.device | None = 'cuda',allow_cpu_fallback: bool = False) -> strOverview
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 FalseReturns
resolve_inference_dtype
def resolve_inference_dtype(device: str | torch.device,dtype: str | torch.dtype | None = 'auto',strict: bool = True) -> torch.dtypeOverview
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.devicedtypestr | torch.dtype | Nonedefault 'auto'strictbooldefault TrueReturns
run_logged_subprocess
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]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 | Pathstderr_pathstr | Pathcwdstr | Path | Nonedefault NoneenvMapping[str, str] | Nonedefault Nonetimeoutfloat | Nonedefault Noneshellbooldefault Falseappendbooldefault Falsestart_new_sessionbool | Nonedefault NoneReturns
run_torchrun_module
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]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
modulestrnproc_per_nodeintargsSequence[str]default ()envMapping[str, str] | Nonedefault Nonepython_executablestrdefault sys.executableReturns
terminate_process_group
def terminate_process_group(process: subprocess.Popen[Any],grace_seconds: float = 3.0) -> NoneOverview
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.0Returns
terminate_process_tree
def terminate_process_tree(process: subprocess.Popen[Any],grace_seconds: float = 3.0) -> NoneOverview
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.0Returns
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)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 Noneflops_estimateint | Nonedefault Noneparameter_countint | Nonedefault Nonetorchprofile_versionstr | Nonedefault Nonemodel_classstr | Nonedefault Noneerrorstr | Nonedefault NoneMethods
Return a JSON-compatible representation suitable for result payloads.
Returns
torchrun_module_command
def torchrun_module_command(module: str,nproc_per_node: int,args: Sequence[str] = (),python_executable: str = sys.executable) -> list[str]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
modulestrnproc_per_nodeintargsSequence[str]default ()python_executablestrdefault sys.executableReturns
utc_now_iso
def utc_now_iso() -> strReturn 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
def worldfoundry_inference_context() -> Iterator[None]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
class WorldFoundryInferenceInfraState(installed: bool = False,sdpa_patched: bool = False,attention_backend: str = 'auto',matmul_precision: str = 'high',tf32_enabled: bool = True)Observable process-wide inference acceleration state. Belongs to Core inference runtime (process setup, compile, timers, realtime).
Attributes
installedbooldefault Falseinstall_worldfoundry_inference_infra ran.sdpa_patchedbooldefault Falseattention_backendstrdefault 'auto'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'highest / high / medium`).tf32_enabledbooldefault Truedef wrap_runner_for_worldfoundry_core(runner: Any) -> AnyOverview
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
runnerAnyReturns
write_jsonl_event
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]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]levelstreventstrmessagestrlogger_namestrdefault 'worldfoundry'exceptionBaseException | str | Nonedefault NonefieldsAny