Core acceleration and memory

Cross-step caches, token pruning, fused kernels, VRAM lifecycle wrappers, disk maps, and memory stores.

On this page

Core separates exact implementation acceleration from approximation policy. Fused kernels and placement changes aim to preserve model semantics. Cross-step caches and token pruning intentionally trade computation for an approximation and therefore expose thresholds, retained ratios, events, and reset boundaries that integrations can evaluate.

Cross-step cache example

import torch

from worldfoundry.core.acceleration import FixedStepCache

cache = FixedStepCache(
    skip_steps={1, 3},
    dense_first=1,
    dense_last=1,
    total_steps=5,
)
calls = []

with torch.no_grad():
    outputs = []
    for step in range(5):
        def compute(step=step):
            calls.append(step)
            return torch.tensor([float(step)])

        outputs.append(cache.run(step, compute))

assert calls == [0, 2, 4]  # boundary steps remain dense
assert [event.hit for event in cache.events] == [False, True, False, True, False]

Caches disable replay while autograd is enabled. Call reset() between independent denoising trajectories; otherwise prior residuals become state for the next request. Treat the event stream as evidence during latency/quality evaluation rather than assuming requested skip steps were all used.

Token pruning lifecycle

select_token_indices is stateless. prune_tokens returns compact data plus TokenPruneState, and restore_tokens scatters processed tokens back, filling dropped positions from compensation or zeros. TokenPruner adds previous-step compensation: its first call records a dense segment, later calls can prune, and every prune must be paired with restore under the same key.

VRAM placement state

enable_vram_management replaces classes listed in module_map with wrappers such as AutoWrappedLinear. Each wrapper can use separate offload, onload, preparing, and computation dtype/device pairs. Disk-backed wrappers resolve parameter names through DiskMap; ordinary wrappers move or copy tensors between devices.

This transformation mutates module identity and should normally run once during model construction. The module-map order matters for overlapping classes. A placement configuration is not automatically safe for a new architecture: validate peak memory, transfer overlap, output equality/tolerance, and behavior when the configured VRAM limit is reached.

Memory records versus VRAM

The BaseMemory and MemoryStore APIs represent retrievable world-model memory records. They do not manage GPU allocation. VRAM wrappers manage parameter placement but do not provide semantic retrieval. Keeping those meanings separate prevents a “memory” setting from being applied at the wrong layer.

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.

26 public symbols

class AdaptiveResidualCache(threshold: float,warmup_steps: int = 1,max_consecutive_hits: int = 3,dense_last: int = 1,total_steps: int | None = None,subsample: int = 1,eps: float = 1e-06)
worldfoundry.core.accelerationfrom worldfoundry.core.acceleration import AdaptiveResidualCache

Overview

Reuse a model residual while accumulated input change stays small. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels).

Source docstring

Reuse a model residual while accumulated input change stays small.

Warm up densely, estimate normalized change from a cheap signal, accumulate it across steps, and replay the last dense residual until the threshold or consecutive-hit cap is reached.

Parameters

thresholdfloat
warmup_stepsintdefault 1
max_consecutive_hitsintdefault 3
dense_lastintdefault 1
total_stepsint | Nonedefault None
subsampleintdefault 1
epsfloatdefault 1e-06

Methods

methreset() -> NoneSource

Clear residual and accumulator so a new clip cannot reuse the last one.

Returns

None
methrun(step: int,signal: torch.Tensor,compute_residual: Callable[[], torch.Tensor],total_steps: int | None = None) -> torch.TensorSource

Return a dense or cached residual for one denoising step.

Parameters

stepint
signaltorch.Tensor
compute_residualCallable[[], torch.Tensor]
total_stepsint | Nonedefault None

Returns

torch.Tensor
class AutoTorchModule(offload_dtype: torch.dtype = None,offload_device: Union[str, torch.device] = None,onload_dtype: torch.dtype = None,onload_device: Union[str, torch.device] = None,preparing_dtype: torch.dtype = None,preparing_device: Union[str, torch.device] = None,computation_dtype: torch.dtype = None,computation_device: Union[str, torch.device] = None,vram_limit: float = None)
worldfoundry.corefrom worldfoundry.core import AutoTorchModule

Overview

Base state machine for modules that move between memory tiers. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels).

Source docstring

Base state machine for modules that move between memory tiers.

`state is 0 while offloaded, 1 while onloaded, and 2` while kept on the computation device. Subclasses decide whether transitions copy tensors, materialize them from disk, or use temporary computation weights.

Parameters

offload_dtypetorch.dtypedefault None
Storage dtype while the module is inactive.
offload_deviceUnion[str, torch.device]default None
Storage device while inactive; subclasses may also accept the sentinel `"disk"`.
onload_dtypetorch.dtypedefault None
Dtype after the first prefetch transition.
onload_deviceUnion[str, torch.device]default None
Device used for prefetched weights.
preparing_dtypetorch.dtypedefault None
Dtype used by the optional second prefetch stage.
preparing_deviceUnion[str, torch.device]default None
Device used by the preparing stage.
computation_dtypetorch.dtypedefault None
Dtype used for the actual forward operation.
computation_deviceUnion[str, torch.device]default None
Device used for the actual forward operation.
vram_limitfloatdefault None
Optional used-memory limit in GiB. Below the limit, wrappers may keep prepared weights resident.

Methods

methset_dtype_and_device(offload_dtype: torch.dtype = None,offload_device: Union[str, torch.device] = None,onload_dtype: torch.dtype = None,onload_device: Union[str, torch.device] = None,preparing_dtype: torch.dtype = None,preparing_device: Union[str, torch.device] = None,computation_dtype: torch.dtype = None,computation_device: Union[str, torch.device] = None,vram_limit: float = None)Source

Update lifecycle placement, defaulting omitted stages to computation placement.

Parameters

offload_dtypetorch.dtypedefault None
offload_deviceUnion[str, torch.device]default None
onload_dtypetorch.dtypedefault None
onload_deviceUnion[str, torch.device]default None
preparing_dtypetorch.dtypedefault None
preparing_deviceUnion[str, torch.device]default None
computation_dtypetorch.dtypedefault None
computation_deviceUnion[str, torch.device]default None
vram_limitfloatdefault None
methcast_to(weight,dtype,device)Source

Copy one tensor to `dtype and device` without mutating the source.

Parameters

weight
dtype
device
methcheck_free_vram()Source

Return whether current accelerator usage is below `vram_limit`.

methoffload()Source

Move managed parameters to the inactive placement and set state 0.

methonload()Source

Move managed parameters to the first prefetch placement and set state 1.

methkeep()Source

Keep managed parameters at computation placement and set state 2.

methparam_name(name)Source

Return the fully qualified checkpoint key for a local parameter name.

Parameters

name
class AutoWrappedLinear(module: torch.nn.Linear,offload_dtype: torch.dtype = None,offload_device: Union[str, torch.device] = None,onload_dtype: torch.dtype = None,onload_device: Union[str, torch.device] = None,preparing_dtype: torch.dtype = None,preparing_device: Union[str, torch.device] = None,computation_dtype: torch.dtype = None,computation_device: Union[str, torch.device] = None,vram_limit: float = None,name: str = '',disk_map: DiskMap = None,**kwargs)
worldfoundry.corefrom worldfoundry.core import AutoWrappedLinear

Linear-layer wrapper with staged placement, disk loading, FP8, and LoRA support. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels).

Parameters

moduletorch.nn.Linear
Source `torch.nn.Linear` whose parameters are reused.
offload_dtypetorch.dtypedefault None
Inactive storage dtype or `"disk"`.
offload_deviceUnion[str, torch.device]default None
Inactive storage device or `"disk"`.
onload_dtypetorch.dtypedefault None
First prefetch dtype.
onload_deviceUnion[str, torch.device]default None
First prefetch device.
preparing_dtypetorch.dtypedefault None
Second prefetch dtype.
preparing_deviceUnion[str, torch.device]default None
Second prefetch device.
computation_dtypetorch.dtypedefault None
Matmul dtype; supported FP8 dtypes use scaled MM.
computation_deviceUnion[str, torch.device]default None
Matmul device.
vram_limitfloatdefault None
Optional used-memory limit in GiB.
namestrdefault ''
Qualified checkpoint prefix for weight and bias.
disk_mapDiskMapdefault None
Required lazy tensor map when disk offload is selected.
kwargs
Reserved for module-map compatibility.

Methods

methfp8_linear(input: torch.Tensor,weight: torch.Tensor,bias: torch.Tensor = None) -> torch.TensorSource

Overview

Row-wise scaled FP8 matmul via `torch._scaled_mm`.

Source docstring

Row-wise scaled FP8 matmul via `torch._scaled_mm`.

Scales are the exact values passed to the kernel so dequantization matches the quantization (CC-28). `e4m3fnuz halves the representable max; that factor is baked into fp8_max` and recovered by the kernel scales, not a post-hoc multiply.

Parameters

inputtorch.Tensor
weighttorch.Tensor
biastorch.Tensordefault None

Returns

torch.Tensor
methload_from_disk(torch_dtype,device,assign = True)Source

Overview

Fetch `name.weight / name.bias` from the disk map.

Source docstring

Fetch `name.weight / name.bias` from the disk map.

`assign=False` returns tensors without mutating this module so a temporary compute copy can leave the stored weights on meta.

Parameters

torch_dtype
device
assigndefault True
methoffload()Source

Drop to meta on disk offload; otherwise move this Linear to offload placement.

methonload()Source

Prefetch this Linear from disk or move from offload; skip a still-disk target.

methpreparing()Source

Second-stage prefetch for this Linear; materialize only when leaving disk.

methcomputation()Source

Overview

Return weight/bias at compute placement without permanently leaving the current state.

Source docstring

Return weight/bias at compute placement without permanently leaving the current state.

`assign=False` on the disk path so the stored Linear stays on meta.

methlinear_forward(x,weight,bias)Source

Dense GEMM, or the FP8 scaled path when `computation_dtype` is float8.

Parameters

x
weight
bias
methlora_forward(x,out)Source

Overview

Add LoRA deltas after the base linear so merge order matches PEFT (B @ A).

Source docstring

Add LoRA deltas after the base linear so merge order matches PEFT (B @ A).

A custom `lora_merger` stacks adapters instead of summing, for multi-adapter blends that are not a simple scale.

Parameters

x
out
methforward(x,*args,**kwargs)Source

Overview

Promote when VRAM allows, run the Linear, then apply LoRA on the output.

Source docstring

Promote when VRAM allows, run the Linear, then apply LoRA on the output.

LoRA is applied after the base GEMM so the merge order matches PEFT (delta on the activation, not a second fused weight).

Parameters

x
args
kwargs
class AutoWrappedModule(module: torch.nn.Module,offload_dtype: torch.dtype = None,offload_device: Union[str, torch.device] = None,onload_dtype: torch.dtype = None,onload_device: Union[str, torch.device] = None,preparing_dtype: torch.dtype = None,preparing_device: Union[str, torch.device] = None,computation_dtype: torch.dtype = None,computation_device: Union[str, torch.device] = None,vram_limit: float = None,name: str = '',disk_map: DiskMap = None,**kwargs)
worldfoundry.corefrom worldfoundry.core import AutoWrappedModule

Overview

Wrap an arbitrary module with staged CPU/GPU/disk weight movement. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels).

Source docstring

Wrap an arbitrary module with staged CPU/GPU/disk weight movement.

Forward calls opportunistically prepare weights, materialize a computation copy only when placement differs, and then delegate to the wrapped module. Attribute access falls through to the wrapped module so model code can keep using its original interface.

Parameters

moduletorch.nn.Module
Original PyTorch module.
offload_dtypetorch.dtypedefault None
Inactive storage dtype or `"disk"`.
offload_deviceUnion[str, torch.device]default None
Inactive storage device or `"disk"`.
onload_dtypetorch.dtypedefault None
First-stage prefetch dtype.
onload_deviceUnion[str, torch.device]default None
First-stage prefetch device.
preparing_dtypetorch.dtypedefault None
Second-stage prefetch dtype.
preparing_deviceUnion[str, torch.device]default None
Second-stage prefetch device.
computation_dtypetorch.dtypedefault None
Forward-pass dtype.
computation_deviceUnion[str, torch.device]default None
Forward-pass device.
vram_limitfloatdefault None
Optional used-memory limit in GiB.
namestrdefault ''
Qualified module name used to resolve disk-map keys.
disk_mapDiskMapdefault None
Lazy checkpoint tensor mapping required for disk offload.
kwargs
Reserved for wrapper-compatible module maps.

Methods

methload_from_disk(torch_dtype,device,copy_module = False)Source

Overview

Materialize disk-backed parameters onto *device*; buffers stay resident.

Source docstring

Materialize disk-backed parameters onto *device*; buffers stay resident.

Non-persistent buffers cannot be reconstructed from a state dict, so they are never replaced. `copy_module=True` clones first so the stored module can remain on meta after a temporary compute load.

Parameters

torch_dtype
device
copy_moduledefault False
methoffload_to_disk(model: torch.nn.Module)Source

Replace disk-backed parameters with meta placeholders, retaining buffers.

Parameters

modeltorch.nn.Module
methoffload()Source

Overview

Return to inactive placement: meta placeholders on disk, else `.to(offload)`.

Source docstring

Return to inactive placement: meta placeholders on disk, else `.to(offload)`.

Disk offload must not `.to(cpu)` — that would materialize the full module and defeat the mmap path.

methonload()Source

Prefetch from disk or move from offload; skip when the target is still disk.

methpreparing()Source

Second-stage prefetch; materialize only when leaving disk for a real device.

methcast_to(module,dtype,device)Source

Deep-copy then move so the stored offload weights are not mutated in place.

Parameters

module
dtype
device
methcomputation()Source

Overview

Return a module at compute placement without permanently leaving the current state.

Source docstring

Return a module at compute placement without permanently leaving the current state.

Reuses `self.module when dtype/device already match. Disk + copy keeps the stored module on meta. Otherwise :meth:cast_to` clones.

methforward(*args,**kwargs)Source

Promote to preparing when VRAM headroom allows, then run a compute copy.

Parameters

args
kwargs
class AutoWrappedNonRecurseModule(module: torch.nn.Module,offload_dtype: torch.dtype = None,offload_device: Union[str, torch.device] = None,onload_dtype: torch.dtype = None,onload_device: Union[str, torch.device] = None,preparing_dtype: torch.dtype = None,preparing_device: Union[str, torch.device] = None,computation_dtype: torch.dtype = None,computation_device: Union[str, torch.device] = None,vram_limit: float = None,name: str = '',disk_map: DiskMap = None,**kwargs)
worldfoundry.corefrom worldfoundry.core import AutoWrappedNonRecurseModule

Manage only a module's direct parameters while its children are wrapped separately. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels).

Parameters

moduletorch.nn.Module
offload_dtypetorch.dtypedefault None
offload_deviceUnion[str, torch.device]default None
onload_dtypetorch.dtypedefault None
onload_deviceUnion[str, torch.device]default None
preparing_dtypetorch.dtypedefault None
preparing_deviceUnion[str, torch.device]default None
computation_dtypetorch.dtypedefault None
computation_deviceUnion[str, torch.device]default None
vram_limitfloatdefault None
namestrdefault ''
disk_mapDiskMapdefault None
kwargs

Methods

methload_from_disk(torch_dtype,device,copy_module = False)Source

Materialize this module's direct parameters only; children own their own maps.

Parameters

torch_dtype
device
copy_moduledefault False
methoffload_to_disk(model: torch.nn.Module)Source

Replace only direct parameters with meta placeholders; children stay untouched.

Parameters

modeltorch.nn.Module
methcast_to(module,dtype,device)Source

Overview

Return *module* unchanged; the architecture owns parameter casts.

Source docstring

Return *module* unchanged; the architecture owns parameter casts.

Deep-copying would pickle child `DiskMap` readers (open safetensors handles) and fail. Callers must already be at compute placement.

Parameters

module
dtype
device
methforward(*args,**kwargs)Source

Overview

In-place disk materialize when offloaded; otherwise the recursive path.

Source docstring

In-place disk materialize when offloaded; otherwise the recursive path.

Deep-copy of a hierarchy that contains independently disk-backed children tries to pickle their open safetensors readers.

Parameters

args
kwargs
class BaseMemory(capacity = None,**kwargs)
worldfoundry.core.memoryfrom worldfoundry.core.memory import BaseMemory

Overview

Generic multimodal memory template for VLM and generative tasks. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels).

Source docstring

Generic multimodal memory template for VLM and generative tasks.

Subclasses implement the five-stage pipeline:

Command methods (mutate state): - `record(data, ...) — ingest raw interaction data. - manage()` — evict, merge, or consolidate memories.

Query methods (read state): - `select(context_query, ...) — retrieve relevant snippets. - compress(memory_items, ...) — distill selected memories. - process(refined_data, ...)` — adapt memories to model input formats.

Parameters

capacitydefault None
kwargs

Methods

propstorage -> list[dict[str, Any]]Source

Live list of persisted record dicts (same object the store holds).

Parameters

self

Returns

list[dict[str, Any]]
methstorage(records: Iterable[Mapping[str, Any]]) -> NoneSource

Replace the backing store, preserving `capacity`.

Parameters

recordsIterable[Mapping[str, Any]]

Returns

None
methcheck_template(**kwargs)Source

Return required record keys and supported content types.

Parameters

kwargs
methappend_record(content: Any,kind: str = 'other',timestamp: int | float | None = None,metadata: Mapping[str, Any] | None = None) -> dict[str, Any]Source

Append one typed record through the bounded store.

Parameters

contentAny
kindstrdefault 'other'
timestampint | float | Nonedefault None
metadataMapping[str, Any] | Nonedefault None

Returns

dict[str, Any]
methlatest_record(prefer_type: str | None = None,metadata: Mapping[str, Any] | None = None) -> dict[str, Any] | NoneSource

Return the newest matching record, or `None`.

Parameters

prefer_typestr | Nonedefault None
metadataMapping[str, Any] | Nonedefault None

Returns

dict[str, Any] | None
methreset_records() -> NoneSource

Clear every stored record.

Returns

None
methrecord(data,metadata = None,**kwargs)Source

Ingest raw interaction data and assign metadata tags.

Parameters

data
metadatadefault None
kwargs
methselect(context_query,**kwargs)Source

Retrieve memory snippets relevant to the current task context.

Parameters

context_query
kwargs
methcompress(_memory_items,**kwargs)Source

Distill selected memories to reduce dimensionality or token count.

Parameters

_memory_items
kwargs
methprocess(_refined_data,_target_format = 'kv_cache',**kwargs)Source

Convert refined memories into a model-ready format such as KV cache.

Parameters

_refined_data
_target_formatdefault 'kv_cache'
kwargs
methmanage(**kwargs)Source

Maintain memory lifecycle: eviction, merging, and STM→LTM transfer.

Parameters

kwargs
class DiskMap(path,device,torch_dtype = None,state_dict_converter = None,buffer_size = 10 ** 9)
worldfoundry.corefrom worldfoundry.core import DiskMap

Overview

Lazy mapping from checkpoint parameter names to materialized tensors. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels).

Source docstring

Lazy mapping from checkpoint parameter names to materialized tensors.

Safetensors files remain memory-mapped and individual weights are loaded on lookup. PyTorch binary checkpoints use an in-memory compatibility loader. The mapping may apply a state-dict converter and periodically reopen files after `buffer_size` tensor elements have been materialized.

Parameters

path
Checkpoint path or list of paths.
device
Device on which fetched tensors are materialized.
torch_dtypedefault None
Optional dtype conversion applied on lookup.
state_dict_converterdefault None
Optional callable that remaps public model keys to keys stored in the checkpoint.
buffer_sizedefault 10 ** 9
Number of fetched tensor elements after which file handles are refreshed.

Methods

methflush_files()Source

Open or refresh checkpoint readers and reset the materialized-element count.

methfetch_rename_dict(state_dict_converter)Source

Build the optional model-key to checkpoint-key mapping.

Parameters

state_dict_converter
def enable_layerwise_cpu_offload(model: nn.Module,layer_container: str | None = None,device: torch.device | str | None = None,pin_memory: bool = True,reuse_buffers: bool = False) -> LayerwiseOffloadHandle
worldfoundry.corefrom worldfoundry.core import enable_layerwise_cpu_offload

Overview

Attach hooks to a ModuleList or an explicitly named Sequential stack. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels). Annotated return type: LayerwiseOffloadHandle.

Source docstring

Attach hooks to a ModuleList or an explicitly named Sequential stack.

The helper keeps parameters on CPU and moves one layer at a time to CUDA. The next layer is prefetched on a separate CUDA stream while the current layer runs. It is intentionally opt-in and returns a disabled handle on non-CUDA systems. Keep the returned handle if you need to switch the model back to full-device residency later via `handle.disable(). Opt in with reuse_buffers=True` to pack contiguous parameters into CPU storage and two reusable CUDA slots. The per-parameter path is the default; non-contiguous weights also retain that path to preserve their layout. The reusable path is inference-only and forbids shared parameter storage across layers. Its mutation scope still supports in-place weight edits.

Parameters

modelnn.Module
layer_containerstr | Nonedefault None
devicetorch.device | str | Nonedefault None
pin_memorybooldefault True
reuse_buffersbooldefault False
def enable_vram_management(model: torch.nn.Module,module_map: dict,vram_config: dict,vram_limit = None,disk_map = None,max_num_param = None,overflow_vram_config: dict | None = None,**kwargs)
worldfoundry.core.vramfrom worldfoundry.core.vram import enable_vram_management

Install staged VRAM management on a model and return that model. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels).

Parameters

modeltorch.nn.Module
Model to wrap. It may be replaced when its own class appears in `module_map`; otherwise matching descendants are mutated.
module_mapdict
Mapping from original module classes to wrapper classes, for example `{torch.nn.Linear: AutoWrappedLinear}`.
vram_configdict
Dictionary containing offload, onload, preparing, and computation dtype/device pairs.
vram_limitdefault None
Optional used-memory limit in GiB.
disk_mapdefault None
Lazy checkpoint mapping used by disk-backed wrappers.
max_num_paramdefault None
Optional parameter budget for the primary policy.
overflow_vram_configdict | Nonedefault None
Placement used after `max_num_param`.
kwargs
Extra wrapper constructor arguments.

Returns

The managed model with `vram_management_enabled set to True`.

Notes

`module_map` order matters when source classes overlap. Configure complete placement keys before calling; this function changes module identity and is normally run once during model construction.

def enable_vram_management_recursively(model: torch.nn.Module,module_map: dict,vram_config: dict,vram_limit = None,name_prefix = '',disk_map = None,max_num_param = None,overflow_vram_config: dict | None = None,total_num_param = 0,**kwargs)
worldfoundry.core.vramfrom worldfoundry.core.vram import enable_vram_management_recursively

Replace matching descendants with lifecycle-aware wrapper modules. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels).

Parameters

modeltorch.nn.Module
Root module mutated in place.
module_mapdict
Mapping from source module classes to wrapper classes.
vram_configdict
Default offload/onload/preparing/computation placements.
vram_limitdefault None
Optional used-memory limit in GiB forwarded to wrappers.
name_prefixdefault ''
Prefix used when resolving checkpoint keys through a `DiskMap`.
disk_mapdefault None
Optional lazy checkpoint mapping for disk-backed wrappers.
max_num_paramdefault None
Parameter budget that switches later modules to `overflow_vram_config`.
overflow_vram_configdict | Nonedefault None
Placement policy used after the parameter budget.
total_num_paramdefault 0
Running parameter count for recursive calls.
kwargs
Extra wrapper constructor arguments.

Returns

Total number of parameters replaced at or below this module.

Notes

The function mutates child modules. Most callers should use `enable_vram_management so the root itself is handled correctly and the vram_management_enabled` marker is installed.

def fill_vram_config(model,vram_config)
worldfoundry.core.vramfrom worldfoundry.core.vram import fill_vram_config

Collapse a placement policy when the root module is wrapped as one unit. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels).

Parameters

model
vram_config
class FixedStepCache(skip_steps: Iterable[int] = (),delta_scale: float = 0.0,dense_first: int = 1,dense_last: int = 1,total_steps: int | None = None)
worldfoundry.core.accelerationfrom worldfoundry.core.acceleration import FixedStepCache

Overview

Reuse a previous denoiser output on an explicit set of steps. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels).

Source docstring

Reuse a previous denoiser output on an explicit set of steps.

`delta_scale=0` replays the last dense output. A non-zero value performs first-order extrapolation from the two latest dense outputs.

Parameters

skip_stepsIterable[int]default ()
delta_scalefloatdefault 0.0
dense_firstintdefault 1
dense_lastintdefault 1
total_stepsint | Nonedefault None

Methods

methreset() -> NoneSource

Drop stored outputs so the next `run` is a seed, not a stale hit.

Returns

None
methrun(step: int,compute: Callable[[], T],total_steps: int | None = None) -> TSource

Compute or replay one step output.

Parameters

stepint
computeCallable[[], T]
total_stepsint | Nonedefault None

Returns

T
def init_weights_on_device(device = torch.device('meta'),include_buffers: bool = False)
worldfoundry.corefrom worldfoundry.core import init_weights_on_device

Temporarily redirect newly registered module weights to one device. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels).

Parameters

devicedefault torch.device('meta')
Destination for parameters created inside the context. The default `meta` device skips real allocation and initialization.
include_buffersbooldefault False
Also redirect registered buffers and common tensor constructors. Leave disabled unless module construction allocates large persistent buffers.

Returns

Control while PyTorch registration hooks are patched.

Notes

Global PyTorch hooks are restored in `finally`. This context is not intended to overlap across threads.

def layer_norm_scale_shift(x: torch.Tensor,scale: torch.Tensor,shift: torch.Tensor,eps: float = 1e-06,upcast: bool = False,backend: str | None = None) -> torch.Tensor
worldfoundry.core.kernelsfrom worldfoundry.core.kernels import layer_norm_scale_shift

Fuse affine-free LayerNorm with AdaLN scale and shift. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels). Annotated return type: torch.Tensor.

Parameters

xtorch.Tensor
scaletorch.Tensor
shifttorch.Tensor
epsfloatdefault 1e-06
upcastbooldefault False
backendstr | Nonedefault None

Returns

torch.Tensor
def layerwise_offload_mutation_scope(module: nn.Module) -> Iterator[None]
worldfoundry.corefrom worldfoundry.core import layerwise_offload_mutation_scope

Overview

Temporarily materialize offloaded parameters for in-place mutations. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels). Annotated return type: Iterator[None].

Parameters

modulenn.Module

Returns

Iterator[None]
class LayerwiseOffloadHandle(enabled: bool,layer_count: int,reason: str = '')
worldfoundry.corefrom worldfoundry.core import LayerwiseOffloadHandle

Overview

Handle returned by `enable_layerwise_cpu_offload`. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels).

Source docstring

Handle returned by `enable_layerwise_cpu_offload`.

Holds the registered hook handles so the offload can be undone with :meth:disable (CC-27); previously the `RemovableHandle` objects were dropped and a model could never leave offload mode without a rebuild.

Attributes

enabledbool
layer_countint
reasonstrdefault ''

Methods

methreset_request_window() -> NoneSource

Reset request-local counters without discarding a prefetched layer.

Returns

None
methreport() -> dict[str, Any]Source

Overview

Return auditable lifetime and request-local execution evidence.

Source docstring

Return auditable lifetime and request-local execution evidence.

`enabled only proves that hooks were installed. effective is true after a forward actually used the two-layer CUDA window with asynchronous H2D copies and no emergency synchronous materialization. Pageable host tensors are surfaced explicitly because non_blocking=True` alone does not prove copy/compute overlap.

Returns

dict[str, Any]
methdisable() -> boolSource

Overview

Remove offload hooks and restore real parameters onto each layer.

Source docstring

Remove offload hooks and restore real parameters onto each layer.

Parameters are restored from the CPU master copies (on CPU); move the model to the desired device afterwards. Returns True when hooks were removed. Handles created for an already-enabled model (`reason="already enabled"`) do not own hooks and return False.

Returns

bool
class MemoryStore(capacity: int | None = None,records: Iterable[Mapping[str, Any] | MemoryRecord] = ())
worldfoundry.core.memoryfrom worldfoundry.core.memory import MemoryStore

Bounded in-process memory store used by all concrete WorldFoundry memories. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels).

Parameters

capacityint | Nonedefault None
recordsIterable[Mapping[str, Any] | MemoryRecord]default ()

Methods

methappend(content: Any,kind: str = 'other',timestamp: int | float | None = None,metadata: Mapping[str, Any] | None = None,score: float | None = None) -> dict[str, Any]Source

Append a new record; *timestamp* defaults to the current length.

Parameters

contentAny
kindstrdefault 'other'
timestampint | float | Nonedefault None
metadataMapping[str, Any] | Nonedefault None
scorefloat | Nonedefault None

Returns

dict[str, Any]
methappend_record(record: Mapping[str, Any] | MemoryRecord) -> dict[str, Any]Source

Normalize *record* to a dict, append it, and evict if over capacity.

Parameters

recordMapping[str, Any] | MemoryRecord

Returns

dict[str, Any]
methlatest(prefer_type: str | None = None,metadata: Mapping[str, Any] | None = None) -> dict[str, Any] | NoneSource

Return the newest record matching optional type and metadata filters.

Parameters

prefer_typestr | Nonedefault None
metadataMapping[str, Any] | Nonedefault None

Returns

dict[str, Any] | None
methselect(query: MemoryQuery | None = None,**overrides: Any) -> MemorySelectionSource

Rank stored records and return the top-*query.top_k* matches.

Parameters

queryMemoryQuery | Nonedefault None
overridesAny

Returns

MemorySelection
methevict() -> NoneSource

Drop oldest records until `len(self) <= capacity` (no-op if unbounded).

Returns

None
methreset() -> NoneSource

Remove every stored record.

Returns

None
methreplace(records: Iterable[Mapping[str, Any] | MemoryRecord]) -> NoneSource

Clear the store and append *records* in order.

Parameters

recordsIterable[Mapping[str, Any] | MemoryRecord]

Returns

None
def prune_tokens(hidden_states: torch.Tensor,keep_ratio: float,method: TokenScoreMethod | str = 'feat_norm',seq_dim: int = 1,start: int = 0,end: int | None = None,previous_velocity: torch.Tensor | None = None) -> tuple[torch.Tensor, TokenPruneState]
worldfoundry.core.accelerationfrom worldfoundry.core.acceleration import prune_tokens

Overview

Gather the selected part of a token segment before expensive blocks. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels). Annotated return type: tuple[torch.Tensor, TokenPruneState].

Parameters

hidden_statestorch.Tensor
keep_ratiofloat
methodTokenScoreMethod | strdefault 'feat_norm'
seq_dimintdefault 1
startintdefault 0
endint | Nonedefault None
previous_velocitytorch.Tensor | Nonedefault None

Returns

tuple[torch.Tensor, TokenPruneState]
def residual_gate_add(residual: torch.Tensor,update: torch.Tensor,gate: torch.Tensor,backend: str | None = None) -> torch.Tensor
worldfoundry.core.kernelsfrom worldfoundry.core.kernels import residual_gate_add

Return `residual + update * gate with broadcast-aware fusion. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels). Annotated return type: torch.Tensor`.

Parameters

residualtorch.Tensor
updatetorch.Tensor
gatetorch.Tensor
backendstr | Nonedefault None

Returns

torch.Tensor
def restore_tokens(processed: torch.Tensor,state: TokenPruneState,compensation: torch.Tensor | None = None) -> torch.Tensor
worldfoundry.core.accelerationfrom worldfoundry.core.acceleration import restore_tokens

Overview

Scatter processed tokens and restore dropped tokens from prior state. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels). Annotated return type: torch.Tensor.

Source docstring

Scatter processed tokens and restore dropped tokens from prior state.

`compensation` is the previous full segment in the original tensor layout. If omitted, dropped tokens are zero-filled.

Parameters

processedtorch.Tensor
compensationtorch.Tensor | Nonedefault None

Returns

torch.Tensor
def routed_swiglu_moe(hidden_states: torch.Tensor,routing_weights: torch.Tensor,selected_experts: torch.Tensor,gate_weight: torch.Tensor,up_weight: torch.Tensor,down_weight: torch.Tensor,workspace: dict[str, torch.Tensor] | Callable[[], dict[str, torch.Tensor]] | None = None,allow_triton: bool | None = None) -> torch.Tensor
worldfoundry.corefrom worldfoundry.core import routed_swiglu_moe

Overview

Dispatch packed SwiGLU MoE to Triton or the portable PyTorch reference. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels). Annotated return type: torch.Tensor.

Parameters

hidden_statestorch.Tensor
routing_weightstorch.Tensor
selected_expertstorch.Tensor
gate_weighttorch.Tensor
up_weighttorch.Tensor
down_weighttorch.Tensor
workspacedict[str, torch.Tensor] | Callable[[], dict[str, torch.Tensor]] | Nonedefault None
allow_tritonbool | Nonedefault None

Returns

torch.Tensor
def routed_swiglu_moe_pytorch(hidden_states: torch.Tensor,routing_weights: torch.Tensor,selected_experts: torch.Tensor,gate_weight: torch.Tensor,up_weight: torch.Tensor,down_weight: torch.Tensor) -> torch.Tensor
worldfoundry.corefrom worldfoundry.core import routed_swiglu_moe_pytorch

Overview

Evaluate a token-routed SwiGLU MoE using portable PyTorch operators. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels). Annotated return type: torch.Tensor.

Parameters

hidden_statestorch.Tensor
Flattened token activations with shape `[T, D]`.
routing_weightstorch.Tensor
Per-route weights with shape `[T, K]`.
selected_expertstorch.Tensor
Expert indices with shape `[T, K]`.
gate_weighttorch.Tensor
Packed gate weights with shape `[E, I, D]`.
up_weighttorch.Tensor
Packed up-projection weights with shape `[E, I, D]`.
down_weighttorch.Tensor
Packed down-projection weights with shape `[E, D, I]`. Only tokens routed to an expert are evaluated for that expert. This keeps the fallback substantially smaller than materializing every expert output, while retaining autograd support and working on CPU, CUDA, and other PyTorch devices.

Returns

torch.Tensor
def select_token_indices(hidden_states: torch.Tensor,keep_ratio: float,method: TokenScoreMethod | str = 'feat_norm',seq_dim: int = 1,previous_velocity: torch.Tensor | None = None,random_seed: int = 42) -> torch.Tensor
worldfoundry.core.accelerationfrom worldfoundry.core.acceleration import select_token_indices

Return ascending indices for tokens retained by a pruning policy. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels). Annotated return type: torch.Tensor.

Parameters

hidden_statestorch.Tensor
keep_ratiofloat
methodTokenScoreMethod | strdefault 'feat_norm'
seq_dimintdefault 1
previous_velocitytorch.Tensor | Nonedefault None
random_seedintdefault 42

Returns

torch.Tensor
def skip_model_initialization(device = torch.device('meta'))
worldfoundry.corefrom worldfoundry.core import skip_model_initialization

Return an allocation-skipping context for constructing checkpoint-backed models. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels).

Parameters

devicedefault torch.device('meta')
class TokenPruner(keep_ratio: float,method: TokenScoreMethod | str = 'feat_norm')
worldfoundry.core.accelerationfrom worldfoundry.core.acceleration import TokenPruner

Stateful previous-step compensation for repeated denoising calls. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels).

Parameters

keep_ratiofloat
methodTokenScoreMethod | strdefault 'feat_norm'

Methods

methreset(key: object | None = None) -> NoneSource

Drop compensation for one branch, or every branch when `key` is omitted.

Parameters

keyobject | Nonedefault None

Returns

None
methprune(hidden_states: torch.Tensor,key: object = 'default',seq_dim: int = 1,start: int = 0,end: int | None = None) -> tuple[torch.Tensor, TokenPruneState | None]Source

Prune after a dense seed call; first use only records compensation.

Parameters

hidden_statestorch.Tensor
keyobjectdefault 'default'
seq_dimintdefault 1
startintdefault 0
endint | Nonedefault None

Returns

tuple[torch.Tensor, TokenPruneState | None]
methrestore(processed: torch.Tensor,state: TokenPruneState | None,key: object = 'default') -> torch.TensorSource

Scatter a pruned step, or snapshot the dense seed as next compensation.

Parameters

processedtorch.Tensor
stateTokenPruneState | None
keyobjectdefault 'default'

Returns

torch.Tensor
class TokenPruneState(indices: torch.Tensor,start: int,end: int,full_length: int,seq_dim: int)
worldfoundry.core.accelerationfrom worldfoundry.core.acceleration import TokenPruneState

Metadata needed to reconstruct a pruned token segment. Belongs to Core acceleration and memory (caches, offload, VRAM, kernels).

Attributes

indicestorch.Tensor
startint
endint
full_lengthint
seq_dimint

Methods

propkept_length -> intSource

Number of retained tokens; used to slice the compacted sequence.

Parameters

self

Returns

int