Core neural network and math

Reusable transformer shapes, patching, layers, normalization, gradients, schedulers, and camera geometry.

On this page

This group contains model-independent tensor operations and small modules. They encode shape contracts that otherwise drift between integrations: attention head width, MLP width, head split/merge, causal masks, image patch grids, normalization, stochastic depth, gradient clipping, rotation conversion, and diffusion scheduling.

Prefer reversible helpers for shape changes

patchify_image returns both token data and a PatchGridSpec. Keep the spec with the tokens; it records the original layout, batch dimensions, patch size, grid, and channel count needed for a checked inverse.

import torch

from worldfoundry.core import patchify_image, unpatchify_image

image = torch.arange(2 * 3 * 8 * 12).reshape(2, 3, 8, 12)
tokens, grid = patchify_image(image, patch_size=(4, 3), layout="nchw")

assert tokens.shape == (2, 8, 36)
restored = unpatchify_image(tokens, grid)
assert torch.equal(restored, image)

unpatchify_image validates the exact token count and vector width instead of silently reshaping incompatible data. split_attention_heads and merge_attention_heads follow the same reversible principle for (..., sequence, hidden) tensors.

Derive dimensions in one place

from worldfoundry.core import transformer_shape_spec

shape = transformer_shape_spec(
    hidden_size=1536,
    num_heads=24,
    mlp_ratio=8 / 3,
    multiple_of=256,
)
assert shape.head_dim == 64
assert shape.mlp_hidden_size % 256 == 0

Use these helpers in config validation and construction, not in a hot per-token loop. They reject non-positive or non-divisible dimensions early and keep model code from carrying slightly different rounding formulas.

Layers versus functional primitives

Mlp, SwiGLUFFN, PatchEmbed, DropPath, and LayerScale are reusable modules. Functional counterparts such as drop_path, rms_norm, layer_scale, and causal_attention_mask are useful when a model already owns parameters or needs a custom wrapper. Camera/rotation functions state their convention in the name; do not mix ZYX, OpenCV, and WXYZ quaternion conventions without an explicit conversion.

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.

38 public symbols

def attention_head_dim(hidden_size: int,num_heads: int) -> int
worldfoundry.corefrom worldfoundry.core import attention_head_dim

Return per-head attention width and validate divisibility. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: int.

Parameters

hidden_sizeint
num_headsint

Returns

int
def causal_attention_mask(query_len: int,key_len: int | None = None,include_self: bool = True) -> np.ndarray
worldfoundry.corefrom worldfoundry.core import causal_attention_mask

Overview

Return a boolean causal mask for query/key lengths. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: np.ndarray.

Source docstring

Return a boolean causal mask for query/key lengths.

When `key_len is larger than query_len`, the mask assumes the query is aligned to the tail of a key/value cache.

Parameters

query_lenint
key_lenint | Nonedefault None
include_selfbooldefault True

Returns

np.ndarray
def clip_grad_norm_(parameters: torch.Tensor | Iterable[torch.Tensor],max_norm: float,norm_type: float = 2.0,error_if_nonfinite: bool = False,foreach: bool | None = None,pp_mesh: torch.distributed.device_mesh.DeviceMesh | None = None) -> torch.Tensor
worldfoundry.corefrom worldfoundry.core import clip_grad_norm_

Overview

Clip gradients and optionally reduce the norm across pipeline-parallel stages. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: torch.Tensor.

Source docstring

Clip gradients and optionally reduce the norm across pipeline-parallel stages.

Same contract as `torch.nn.utils.clip_grad_norm_ plus *pp_mesh*: when set, the local total norm is all-reduced on that DeviceMesh (MAX for inf, SUM of norm**p then **(1/p)` otherwise) before scaling. DTensor norms are converted to a dense tensor first.

Parameters

parameterstorch.Tensor | Iterable[torch.Tensor]
max_normfloat
norm_typefloatdefault 2.0
error_if_nonfinitebooldefault False
foreachbool | Nonedefault None
pp_meshtorch.distributed.device_mesh.DeviceMesh | Nonedefault None

Returns

torch.TensorThe (possibly reduced) total gradient norm.
def clip_grads_with_norm_(parameters: torch.Tensor | Iterable[torch.Tensor],max_norm: float,total_norm: torch.Tensor,foreach: bool | None = None) -> None
worldfoundry.corefrom worldfoundry.core import clip_grads_with_norm_

Overview

Scale parameter gradients in-place using a precomputed total norm. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: None.

Source docstring

Scale parameter gradients in-place using a precomputed total norm.

The coefficient is `min(1, max_norm / (total_norm + 1e-6))`. Foreach multiply is used per device when available. No-op when no parameter has a gradient.

Parameters

parameterstorch.Tensor | Iterable[torch.Tensor]
max_normfloat
total_normtorch.Tensor
foreachbool | Nonedefault None

Returns

None
def drop_path(x: Tensor,drop_prob: float = 0.0,training: bool = False,scale_by_keep: bool = True) -> Tensor
worldfoundry.corefrom worldfoundry.core import drop_path

Functional form of per-sample stochastic depth for residual branches.

Parameters

xTensor
drop_probfloatdefault 0.0
trainingbooldefault False
scale_by_keepbooldefault True

Returns

Tensor
class DropPath(drop_prob: float | None = 0.0,scale_by_keep: bool = True)
worldfoundry.corefrom worldfoundry.core import DropPath

Stochastic depth module that drops residual paths per sample during training.

Parameters

drop_probfloat | Nonedefault 0.0
scale_by_keepbooldefault True

Methods

methforward(x: Tensor) -> TensorSource

No-op in eval; in train, scale surviving samples when requested.

Parameters

xTensor

Returns

Tensor
def euler_angles_to_rotation_matrix_zyx(euler_angles: np.ndarray) -> np.ndarray
worldfoundry.corefrom worldfoundry.core import euler_angles_to_rotation_matrix_zyx

Convert `[x, y, z] Euler angles to Rz @ Ry @ Rx. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: np.ndarray`.

Parameters

euler_anglesnp.ndarray

Returns

np.ndarray
class FlowMatchScheduler(num_inference_steps: int = 100,num_train_timesteps: int = 1000,shift: float = 3.0,sigma_max: float = 1.0,sigma_min: float = 0.003 / 1.002,inverse_timesteps: bool = False,extra_one_step: bool = False,reverse_sigmas: bool = False,exponential_shift: bool = False,exponential_shift_mu: float | None = None,shift_terminal: float | None = None)
worldfoundry.corefrom worldfoundry.core import FlowMatchScheduler

Overview

Flow-matching scheduler shared by bundled video runtimes. Belongs to Core neural-net/math helpers (shared tensor transforms).

Source docstring

Flow-matching scheduler shared by bundled video runtimes.

Why shift exists: a linear sigma grid spends too many steps at high noise for video. `shift * σ / (1 + (shift-1)σ) (or the exponential form) stretches the low-noise end. denoising_strength < 1 starts from an intermediate sigma for img2vid / inpaint. extra_one_step` drops the terminal sample so the last model call is still a real denoise step.

Parameters

num_inference_stepsintdefault 100
num_train_timestepsintdefault 1000
shiftfloatdefault 3.0
sigma_maxfloatdefault 1.0
sigma_minfloatdefault 0.003 / 1.002
inverse_timestepsbooldefault False
extra_one_stepbooldefault False
reverse_sigmasbooldefault False
exponential_shiftbooldefault False
exponential_shift_mufloat | Nonedefault None
shift_terminalfloat | Nonedefault None

Methods

methset_timesteps(num_inference_steps: int = 100,denoising_strength: float = 1.0,training: bool = False,shift: float | None = None,dynamic_shift_len: int | None = None,exponential_shift_mu: float | None = None) -> NoneSource

Rebuild `sigmas / timesteps` for a new step count or shift.

Parameters

num_inference_stepsintdefault 100
denoising_strengthfloatdefault 1.0
trainingbooldefault False
shiftfloat | Nonedefault None
dynamic_shift_lenint | Nonedefault None
exponential_shift_mufloat | Nonedefault None

Returns

None
methstep(model_output,timestep,sample,to_final: bool = False)Source

Overview

One Euler step: `sample + velocity * (σ_next - σ)`.

Source docstring

One Euler step: `sample + velocity * (σ_next - σ)`.

`to_final forces the terminal sigma even mid-schedule (last-step snap). Inverse/reversed calendars use terminal 1.0 instead of 0.0` so the integrator still walks toward clean data.

Parameters

model_output
timestep
sample
to_finalbooldefault False
methreturn_to_timestep(timestep,sample,stabilized_sample)Source

Recover a velocity that maps `sample to stabilized_sample`.

Parameters

timestep
sample
stabilized_sample
methadd_noise(original_samples,noise,timestep)Source

Run the forward corruption process.

Parameters

original_samples
noise
timestep
methtraining_target(sample,noise,timestep)Source

Flow-matching target `noise - sample` (velocity toward noise).

Parameters

sample
noise
timestep
methtraining_weight(timestep)Source

Per-timestep loss weight from the Gaussian bump built in training mode.

Parameters

timestep
smethcalculate_shift(image_seq_len: int,base_seq_len: int = 256,max_seq_len: int = 8192,base_shift: float = 0.5,max_shift: float = 0.9) -> floatSource

Interpolate exponential-shift μ from sequence length (Flux-style).

Parameters

image_seq_lenint
base_seq_lenintdefault 256
max_seq_lenintdefault 8192
base_shiftfloatdefault 0.5
max_shiftfloatdefault 0.9

Returns

float
def get_total_norm(tensors: torch.Tensor | Iterable[torch.Tensor],norm_type: float = 2.0,error_if_nonfinite: bool = False,foreach: bool | None = None) -> torch.Tensor
worldfoundry.corefrom worldfoundry.core import get_total_norm

Overview

Compute the total norm of tensors as if their flattened values were concatenated. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: torch.Tensor.

Source docstring

Compute the total norm of tensors as if their flattened values were concatenated.

Groups tensors by device/dtype and uses `torch._foreach_norm when the device supports it (or *foreach* is forced). Empty input yields a CPU scalar 0.0`. Set *error_if_nonfinite* to raise instead of returning NaN/Inf.

Parameters

tensorstorch.Tensor | Iterable[torch.Tensor]
norm_typefloatdefault 2.0
error_if_nonfinitebooldefault False
foreachbool | Nonedefault None

Returns

torch.Tensor
def layer_scale(value: Any,scale: Any,bias: Any = None) -> Any
worldfoundry.corefrom worldfoundry.core import layer_scale

Apply a stateless elementwise layer-scale transform. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: Any.

Parameters

valueAny
scaleAny
biasAnydefault None

Returns

Any
class LayerScale(dim: int,init_values: Union[float, Tensor] = 1e-05,inplace: bool = False,device = None)
worldfoundry.corefrom worldfoundry.core import LayerScale

Learnable per-channel residual scaling used in modern Vision Transformer blocks.

Parameters

dimint
Channel width of the final tensor dimension.
init_valuesUnion[float, Tensor]default 1e-05
Scalar or per-channel initialization for `gamma`.
inplacebooldefault False
Multiply the input in place during `forward`.
devicedefault None
Optional parameter device.

Methods

methreset_parameters() -> NoneSource

Copy a tensor init or fill a scalar; used after meta-device materialize.

Returns

None
methforward(x: Tensor) -> TensorSource

Scale the final dimension of `x by the learned gamma`.

Parameters

xTensor

Returns

Tensor
methextra_repr() -> strSource

Include init and inplace flags so module printouts distinguish LayerScales.

Returns

str
def merge_attention_heads(value: Any) -> Any
worldfoundry.corefrom worldfoundry.core import merge_attention_heads

Invert `split_attention_heads for (..., heads, seq, head_dim) tensors. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: Any`.

Parameters

valueAny

Returns

Any
class Mlp(in_features: int,hidden_features: Optional[int] = None,out_features: Optional[int] = None,act_layer: Callable[..., nn.Module] = nn.GELU,drop: float | tuple[float, float] = 0.0,bias: bool | tuple[bool, bool] = True,device = None)
worldfoundry.corefrom worldfoundry.core import Mlp

timm-style 2-layer ViT FFN (fc1 → act → fc2); distinct from `SamHeadMLP`. Belongs to Core neural-net/math helpers (shared tensor transforms).

Parameters

in_featuresint
Input width.
hidden_featuresOptional[int]default None
Intermediate width; defaults to `in_features`.
out_featuresOptional[int]default None
Output width; defaults to `in_features`.
act_layerCallable[..., nn.Module]default nn.GELU
Activation module factory between projections.
dropfloat | tuple[float, float]default 0.0
One probability for both dropout sites or a pair for the first and second sites.
biasbool | tuple[bool, bool]default True
One bias flag for both projections or a pair.
devicedefault None
Optional projection parameter device.

Methods

methforward(x: Tensor) -> TensorSource

Apply `fc1 → activation → dropout → fc2 → dropout`.

Parameters

xTensor

Returns

Tensor
def mlp_hidden_size(hidden_size: int,multiplier: float = 4.0,multiple_of: int | None = None) -> int
worldfoundry.corefrom worldfoundry.core import mlp_hidden_size

Compute a feed-forward hidden width with optional upward rounding. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: int.

Parameters

hidden_sizeint
multiplierfloatdefault 4.0
multiple_ofint | Nonedefault None

Returns

int
def named_apply(fn: Callable[..., object],module: nn.Module,name: str = '',depth_first: bool = True,include_root: bool = False) -> nn.Module
worldfoundry.corefrom worldfoundry.core import named_apply

Overview

Apply `fn(module=..., name=...) recursively with stable module names. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: nn.Module`.

Source docstring

Apply `fn(module=..., name=...)` recursively with stable module names.

This is the named equivalent of :meth:torch.nn.Module.apply. By default, children are visited depth-first and the supplied root is omitted, matching the behavior historically used by the DINO-style backbones in WorldFoundry.

Parameters

fnCallable[..., object]
modulenn.Module
namestrdefault ''
depth_firstbooldefault True
include_rootbooldefault False

Returns

nn.Module
def named_camera_trajectory_tensors(trajectory: str,initial_world_to_camera: Any,initial_intrinsic: Any,num_frames: int,movement_distance: float = 0.3,camera_rotation: str = 'center_facing',center_depth: float = 1.0,num_circles: int = 1)
worldfoundry.corefrom worldfoundry.core import named_camera_trajectory_tensors

Overview

Build the eight named GEN3C camera trajectories without a model runtime. Belongs to Core neural-net/math helpers (shared tensor transforms).

Source docstring

Build the eight named GEN3C camera trajectories without a model runtime.

The output is `(world_to_camera, intrinsics) with batched shapes [1,T,4,4] and [1,T,3,3]. Keeping this geometry in core` makes it reusable by camera-conditioned recipes instead of tying it to Cosmos.

Parameters

trajectorystr
initial_world_to_cameraAny
initial_intrinsicAny
num_framesint
movement_distancefloatdefault 0.3
camera_rotationstrdefault 'center_facing'
center_depthfloatdefault 1.0
num_circlesintdefault 1
class PatchEmbed(img_size: Union[int, tuple[int, int]] = 224,patch_size: Union[int, tuple[int, int]] = 16,in_chans: int = 3,embed_dim: int = 768,norm_layer: Optional[Callable[..., nn.Module]] = None,flatten_embedding: bool = True)
worldfoundry.corefrom worldfoundry.core import PatchEmbed

2D image patch embedding: `(B, C, H, W) -> (B, N, D)`. Belongs to Core neural-net/math helpers (shared tensor transforms).

Parameters

img_sizeUnion[int, tuple[int, int]]default 224
Nominal image height/width used to report patch count.
patch_sizeUnion[int, tuple[int, int]]default 16
Convolution kernel/stride height and width.
in_chansintdefault 3
Input channel count.
embed_dimintdefault 768
Output token width.
norm_layerOptional[Callable[..., nn.Module]]default None
Optional normalization factory applied per token.
flatten_embeddingbooldefault True
Return `(B, N, D) when true, otherwise (B, grid_h, grid_w, D)`.

Methods

methreset_parameters() -> NoneSource

Uniform init scaled by fan-in of the patch convolution (checkpoint match).

Returns

None
methforward(x: Tensor) -> TensorSource

Project a divisible NCHW image batch into patch embeddings.

Parameters

xTensor

Returns

Tensor

Raises

ValueError
Runtime height or width is not divisible by patch size.
methflops() -> floatSource

Report conv + optional norm FLOPs for the *nominal* `img_size` grid.

Returns

float
class PatchEmbed_Mlp(img_size: Union[int, tuple[int, int]] = 224,patch_size: Union[int, tuple[int, int]] = 16,in_chans: int = 3,embed_dim: int = 768,norm_layer: Optional[Callable[..., nn.Module]] = None,flatten_embedding: bool = True)
worldfoundry.corefrom worldfoundry.core import PatchEmbed_Mlp

Patch embedding implemented with pixel unshuffle and MLP projection. Belongs to Core neural-net/math helpers (shared tensor transforms).

Parameters

img_sizeUnion[int, tuple[int, int]]default 224
patch_sizeUnion[int, tuple[int, int]]default 16
in_chansintdefault 3
embed_dimintdefault 768
norm_layerOptional[Callable[..., nn.Module]]default None
flatten_embeddingbooldefault True
class PatchGridSpec(original_shape: tuple[int, ...],patch_size: tuple[int, int],layout: ImageLayout = 'nchw')
worldfoundry.corefrom worldfoundry.core import PatchGridSpec

Shape contract needed to invert a 2D image patchification. Belongs to Core neural-net/math helpers (shared tensor transforms).

Attributes

original_shapetuple[int, ...]
patch_sizetuple[int, int]
layoutImageLayoutdefault 'nchw'

Methods

propbatch_shape -> tuple[int, ...]Source

Leading axes before the CHW / HWC triple (may be empty).

Parameters

self

Returns

tuple[int, ...]
propchannels -> intSource

Channel axis selected by `layout` (not always dim 1).

Parameters

self

Returns

int
propspatial_shape -> tuple[int, int]Source

`(H, W)` regardless of NCHW vs NHWC.

Parameters

self

Returns

tuple[int, int]
propgrid_shape -> tuple[int, int]Source

Number of patches along height and width.

Parameters

self

Returns

tuple[int, int]
proppatch_vector_size -> intSource

Flattened per-patch width `C * ph * pw`.

Parameters

self

Returns

int
proppatch_count -> intSource

`grid_h * grid_w` — the sequence length after patchify.

Parameters

self

Returns

int
def patchify_image(value: Any,patch_size: int | Sequence[int],layout: ImageLayout = 'nchw') -> tuple[Any, PatchGridSpec]
worldfoundry.corefrom worldfoundry.core import patchify_image

Overview

Convert an image tensor into flattened 2D patch tokens. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: tuple[Any, PatchGridSpec].

Source docstring

Convert an image tensor into flattened 2D patch tokens.

`layout="nchw" expects (..., C, H, W) and layout="nhwc" expects (..., H, W, C). The returned token tensor has shape (..., grid_h * grid_w, C * patch_h * patch_w)`.

Parameters

valueAny
patch_sizeint | Sequence[int]
layoutImageLayoutdefault 'nchw'

Returns

tuple[Any, PatchGridSpec]
class Permute(dims: tuple[int, ])
worldfoundry.corefrom worldfoundry.core import Permute

Module wrapper around `Tensor.permute`. Belongs to Core neural-net/math helpers (shared tensor transforms).

Attributes

dimstuple[int, ...]

Methods

methforward(value: Tensor) -> TensorSource

Apply the stored axis permutation; no shape validation (caller contract).

Parameters

valueTensor

Returns

Tensor
class PixelUnshuffle(downscale_factor: int)
worldfoundry.corefrom worldfoundry.core import PixelUnshuffle

Module wrapper for `torch.nn.functional.pixel_unshuffle`. Belongs to Core neural-net/math helpers (shared tensor transforms).

Parameters

downscale_factorint

Methods

methforward(value: Tensor) -> TensorSource

Unshuffle `[B, C, H, W]; empty tensors use view` because F.

Parameters

valueTensor

Returns

Tensor

Raises

ValueError
empty input spatial dims are 0 or not divisible by the factor.
def quaternion_xyzw_to_rotation_matrix(quaternions: Tensor) -> Tensor
worldfoundry.corefrom worldfoundry.core import quaternion_xyzw_to_rotation_matrix

Convert `[..., x, y, z, w] quaternions to rotation matrices. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: Tensor`.

Parameters

quaternionsTensor

Returns

Tensor
def ray_condition(K,c2w,H: int,W: int,device,flip_flag = None,use_ray_o: bool = False)
worldfoundry.corefrom worldfoundry.core import ray_condition

Build per-pixel Plucker ray features from intrinsics and camera-to-world poses. Belongs to Core neural-net/math helpers (shared tensor transforms).

Parameters

K
Camera intrinsics in `[fx, fy, cx, cy] layout with shape [B,V,4]. When None`, rays use a constant forward camera-space direction.
c2w
Camera-to-world matrices with shape `[B,V,4,4]`.
Hint
Output grid height.
Wint
Output grid width.
device
Device for generated coordinate grids.
flip_flagdefault None
Optional boolean mask selecting horizontally flipped views.
use_ray_obooldefault False
If true, concatenate `[ray_origin, ray_direction] instead of the Plucker [ray_origin x ray_direction, ray_direction]` form.
def rms_norm(value: Any,weight: Any = None,eps: float = 1e-06) -> Any
worldfoundry.corefrom worldfoundry.core import rms_norm

Apply RMS normalization over the last dimension. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: Any.

Parameters

valueAny
weightAnydefault None
epsfloatdefault 1e-06

Returns

Any
def rotation_matrix_to_euler_angles_opencv(rotation: np.ndarray) -> tuple[float, float, float]
worldfoundry.corefrom worldfoundry.core import rotation_matrix_to_euler_angles_opencv

Return the ZYX angles in OpenCV's `(z, y, x) order. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: tuple[float, float, float]`.

Parameters

rotationnp.ndarray

Returns

tuple[float, float, float]
def rotation_matrix_to_euler_angles_zyx(rotation: np.ndarray) -> np.ndarray
worldfoundry.corefrom worldfoundry.core import rotation_matrix_to_euler_angles_zyx

Convert a 3x3 rotation matrix to `[x, y, z] Euler angles. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: np.ndarray`.

Parameters

rotationnp.ndarray

Returns

np.ndarray
def rotation_matrix_to_quaternion_wxyz(rotation: np.ndarray) -> np.ndarray
worldfoundry.corefrom worldfoundry.core import rotation_matrix_to_quaternion_wxyz

Convert a 3x3 rotation matrix to a normalized `[w, x, y, z] quaternion. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: np.ndarray`.

Parameters

rotationnp.ndarray

Returns

np.ndarray
def rotation_matrix_to_quaternion_xyzw(matrix: Tensor) -> Tensor
worldfoundry.corefrom worldfoundry.core import rotation_matrix_to_quaternion_xyzw

Overview

Convert `[..., 3, 3] rotation matrices to canonical XYZW quaternions. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: Tensor`.

Source docstring

Convert `[..., 3, 3]` rotation matrices to canonical XYZW quaternions.

The implementation chooses the best-conditioned of four equivalent quaternion candidates and keeps gradients well-defined away from zero.

Parameters

matrixTensor

Returns

Tensor
class SchedulerInterface(alphas_cumprod: torch.Tensor)
worldfoundry.corefrom worldfoundry.core import SchedulerInterface

Base interface for diffusion noise schedules. Belongs to Core neural-net/math helpers (shared tensor transforms).

Attributes

alphas_cumprodtorch.Tensor

Methods

methadd_noise(clean_latent: torch.Tensor,noise: torch.Tensor,timestep: torch.Tensor)Source

Run the forward corruption process.

Parameters

clean_latenttorch.Tensor
noisetorch.Tensor
timesteptorch.Tensor
methconvert_x0_to_noise(x0: torch.Tensor,xt: torch.Tensor,timestep: torch.Tensor) -> torch.TensorSource

Convert a clean-data prediction to a noise prediction.

Parameters

x0torch.Tensor
xttorch.Tensor
timesteptorch.Tensor

Returns

torch.Tensor
methconvert_noise_to_x0(noise: torch.Tensor,xt: torch.Tensor,timestep: torch.Tensor) -> torch.TensorSource

Convert a noise prediction to a clean-data prediction.

Parameters

noisetorch.Tensor
xttorch.Tensor
timesteptorch.Tensor

Returns

torch.Tensor
methconvert_velocity_to_x0(velocity: torch.Tensor,xt: torch.Tensor,timestep: torch.Tensor) -> torch.TensorSource

Convert a velocity prediction to a clean-data prediction.

Parameters

velocitytorch.Tensor
xttorch.Tensor
timesteptorch.Tensor

Returns

torch.Tensor
def split_attention_heads(value: Any,num_heads: int) -> Any
worldfoundry.corefrom worldfoundry.core import split_attention_heads

Reshape `(..., seq, hidden) to (..., heads, seq, head_dim). Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: Any`.

Parameters

valueAny
num_headsint

Returns

Any
def standardize_quaternion_xyzw(quaternions: Tensor) -> Tensor
worldfoundry.corefrom worldfoundry.core import standardize_quaternion_xyzw

Choose the equivalent XYZW quaternion whose real part is non-negative. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: Tensor.

Parameters

quaternionsTensor

Returns

Tensor
class SwiGLUFFN(in_features: int,hidden_features: Optional[int] = None,out_features: Optional[int] = None,act_layer: Callable[..., nn.Module] | None = None,drop: float = 0.0,bias: bool = True)
worldfoundry.corefrom worldfoundry.core import SwiGLUFFN

SwiGLU feed-forward layer shared across model integrations.

Parameters

in_featuresint
hidden_featuresOptional[int]default None
out_featuresOptional[int]default None
act_layerCallable[..., nn.Module] | Nonedefault None
dropfloatdefault 0.0
biasbooldefault True

Methods

methforward(x: Tensor) -> TensorSource

Last-dim SwiGLU matching the `w12 / w3` checkpoint split.

Parameters

xTensor

Returns

Tensor
class SwiGLUFFNFused(in_features: int,hidden_features: Optional[int] = None,out_features: Optional[int] = None,act_layer: Callable[..., nn.Module] | None = None,drop: float = 0.0,bias: bool = True)
worldfoundry.corefrom worldfoundry.core import SwiGLUFFNFused

SwiGLU FFN with hidden width rounded for tensor-core-friendly matmuls. Belongs to Core neural-net/math helpers (shared tensor transforms).

Parameters

in_featuresint
Input width.
hidden_featuresOptional[int]default None
Requested hidden width before the SwiGLU 2/3 adjustment and upward rounding to a multiple of eight.
out_featuresOptional[int]default None
Output width; defaults to `in_features`.
act_layerCallable[..., nn.Module] | Nonedefault None
Accepted for MLP-constructor compatibility; unused.
dropfloatdefault 0.0
Accepted for MLP-constructor compatibility; unused.
biasbooldefault True
Enable biases in the fused input and output projections.
def transformer_shape_spec(hidden_size: int,num_heads: int,mlp_ratio: float = 4.0,multiple_of: int | None = None) -> TransformerShapeSpec
worldfoundry.corefrom worldfoundry.core import transformer_shape_spec

Build a reusable shape spec for attention and MLP dimensions. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: TransformerShapeSpec.

Parameters

hidden_sizeint
num_headsint
mlp_ratiofloatdefault 4.0
multiple_ofint | Nonedefault None
class TransformerShapeSpec(hidden_size: int,num_heads: int,head_dim: int,mlp_hidden_size: int)
worldfoundry.corefrom worldfoundry.core import TransformerShapeSpec

Common transformer dimensions derived from hidden size and head count. Belongs to Core neural-net/math helpers (shared tensor transforms).

Attributes

hidden_sizeint
num_headsint
head_dimint
mlp_hidden_sizeint
def unpatchify_image(patches: Any,spec: PatchGridSpec) -> Any
worldfoundry.corefrom worldfoundry.core import unpatchify_image

Invert `patchify_image using the returned PatchGridSpec. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: Any`.

Parameters

patchesAny

Returns

Any
def zero_module(module: nn.Module) -> nn.Module
worldfoundry.corefrom worldfoundry.core import zero_module

Detach and zero all parameters in a module. Belongs to Core neural-net/math helpers (shared tensor transforms). Annotated return type: nn.Module.

Parameters

modulenn.Module

Returns

nn.Module