Core 神经网络与数学

可复用 Transformer 形状、patch、layer、normalization、gradient、scheduler 与相机几何。

本页内容

这一组收录与模型身份无关的张量操作和小型 module。它们固化那些很容易在不同接入中漂移的形状契约:attention head 宽度、MLP 宽度、head 拆分合并、causal mask、图像 patch grid、normalization、stochastic depth、gradient clipping、旋转转换和 diffusion scheduler。

形状变换优先使用可逆 helper

patchify_image 同时返回 token 数据和 PatchGridSpec。应让 spec 与 token 一起流转,因为它记录了经过检查的逆变换所需的原始布局、batch 维、patch size、grid 和 channel 数。

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 会验证准确的 token 数和向量宽度,不会把不兼容数据静默 reshape。split_attention_heads 与 merge_attention_heads 对 (..., sequence, hidden) tensor 采用同样的可逆原则。

在一个地方推导维度

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

这些 helper 适合用于配置验证与构造,不要放进每 token 的热循环。它们会提前拒绝非正数或不可整除的维度,并避免不同模型代码各自携带略有差异的 rounding 公式。

Module 与函数式 primitive

Mlp、SwiGLUFFN、PatchEmbed、DropPath 和 LayerScale 是可复用 module。当模型已经拥有参数或者需要自定义 wrapper 时,可以使用 drop_path、rms_norm、layer_scale 和 causal_attention_mask 等函数式入口。相机与旋转函数会在名称中声明 convention;不要在没有显式转换的情况下混用 ZYX、OpenCV 和 WXYZ quaternion convention。

完整参考

以下为该类别的生成签名。可用本页符号索引跳转;源码链接指向各惰性导出背后的具体实现。

38 个公开符号

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

attention_head_dim — Return per-head attention width and validate divisibility. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:int。

参数

hidden_sizeint
num_headsint

返回值

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

简介

causal_attention_mask — Return a boolean causal mask for query/key lengths. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:np.ndarray。

源码 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.

参数

query_lenint
key_lenint | None默认值 None
include_selfbool默认值 True

返回值

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_

简介

clip_grad_norm_ — Clip gradients and optionally reduce the norm across pipeline-parallel stages. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:torch.Tensor。

源码 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.

参数

parameterstorch.Tensor | Iterable[torch.Tensor]
max_normfloat
norm_typefloat默认值 2.0
error_if_nonfinitebool默认值 False
foreachbool | None默认值 None
pp_meshtorch.distributed.device_mesh.DeviceMesh | None默认值 None

返回值

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_

简介

clip_grads_with_norm_ — Scale parameter gradients in-place using a precomputed total norm. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:None。

源码 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.

参数

parameterstorch.Tensor | Iterable[torch.Tensor]
max_normfloat
total_normtorch.Tensor
foreachbool | None默认值 None

返回值

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

残差分支上按样本 Stochastic Depth 的函数式接口。

参数

xTensor
drop_probfloat默认值 0.0
trainingbool默认值 False
scale_by_keepbool默认值 True

返回值

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

训练时按样本丢弃残差路径的 Stochastic Depth 模块。

参数

drop_probfloat | None默认值 0.0
scale_by_keepbool默认值 True

方法

methforward(x: Tensor) -> Tensor源码

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

参数

xTensor

返回值

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

euler_angles_to_rotation_matrix_zyx — Convert `[x, y, z] Euler angles to Rz @ Ry @ Rx. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:np.ndarray`。

参数

euler_anglesnp.ndarray

返回值

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

简介

FlowMatchScheduler — Flow-matching scheduler shared by bundled video runtimes. 属于 Core 神经网络/数学辅助(共享张量变换)。

源码 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.

参数

num_inference_stepsint默认值 100
num_train_timestepsint默认值 1000
shiftfloat默认值 3.0
sigma_maxfloat默认值 1.0
sigma_minfloat默认值 0.003 / 1.002
inverse_timestepsbool默认值 False
extra_one_stepbool默认值 False
reverse_sigmasbool默认值 False
exponential_shiftbool默认值 False
exponential_shift_mufloat | None默认值 None
shift_terminalfloat | None默认值 None

方法

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) -> None源码

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

参数

num_inference_stepsint默认值 100
denoising_strengthfloat默认值 1.0
trainingbool默认值 False
shiftfloat | None默认值 None
dynamic_shift_lenint | None默认值 None
exponential_shift_mufloat | None默认值 None

返回值

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

简介

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

源码 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.

参数

model_output
timestep
sample
to_finalbool默认值 False
methreturn_to_timestep(timestep,sample,stabilized_sample)源码

return_to_timestep — Recover a velocity that maps `sample to stabilized_sample`.

参数

timestep
sample
stabilized_sample
methadd_noise(original_samples,noise,timestep)源码

add_noise — Run the forward corruption process.

参数

original_samples
noise
timestep
methtraining_target(sample,noise,timestep)源码

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

参数

sample
noise
timestep
methtraining_weight(timestep)源码

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

参数

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) -> float源码

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

参数

image_seq_lenint
base_seq_lenint默认值 256
max_seq_lenint默认值 8192
base_shiftfloat默认值 0.5
max_shiftfloat默认值 0.9

返回值

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

简介

get_total_norm — Compute the total norm of tensors as if their flattened values were concatenated. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:torch.Tensor。

源码 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.

参数

tensorstorch.Tensor | Iterable[torch.Tensor]
norm_typefloat默认值 2.0
error_if_nonfinitebool默认值 False
foreachbool | None默认值 None

返回值

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

layer_scale — Apply a stateless elementwise layer-scale transform. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:Any。

参数

valueAny
scaleAny
biasAny默认值 None

返回值

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

现代 ViT block 中常见的可学习逐通道残差缩放。

参数

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

方法

methreset_parameters() -> None源码

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

返回值

None
methforward(x: Tensor) -> Tensor源码

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

参数

xTensor

返回值

Tensor
methextra_repr() -> str源码

extra_repr — Include init and inplace flags so module printouts distinguish LayerScales.

返回值

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

merge_attention_heads — Invert `split_attention_heads for (..., heads, seq, head_dim) tensors. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:Any`。

参数

valueAny

返回值

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

Mlp — timm-style 2-layer ViT FFN (fc1 → act → fc2); distinct from `SamHeadMLP`. 属于 Core 神经网络/数学辅助(共享张量变换)。

参数

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

方法

methforward(x: Tensor) -> Tensor源码

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

参数

xTensor

返回值

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

mlp_hidden_size — Compute a feed-forward hidden width with optional upward rounding. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:int。

参数

hidden_sizeint
multiplierfloat默认值 4.0
multiple_ofint | None默认值 None

返回值

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

简介

named_apply — Apply `fn(module=..., name=...) recursively with stable module names. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:nn.Module`。

源码 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.

参数

fnCallable[..., object]
modulenn.Module
namestr默认值 ''
depth_firstbool默认值 True
include_rootbool默认值 False

返回值

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

简介

named_camera_trajectory_tensors — Build the eight named GEN3C camera trajectories without a model runtime. 属于 Core 神经网络/数学辅助(共享张量变换)。

源码 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.

参数

trajectorystr
initial_world_to_cameraAny
initial_intrinsicAny
num_framesint
movement_distancefloat默认值 0.3
camera_rotationstr默认值 'center_facing'
center_depthfloat默认值 1.0
num_circlesint默认值 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

PatchEmbed — 2D image patch embedding: `(B, C, H, W) -> (B, N, D)`. 属于 Core 神经网络/数学辅助(共享张量变换)。

参数

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

方法

methreset_parameters() -> None源码

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

返回值

None
methforward(x: Tensor) -> Tensor源码

forward — Project a divisible NCHW image batch into patch embeddings.

参数

xTensor

返回值

Tensor

异常

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

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

返回值

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

PatchEmbed_Mlp — Patch embedding implemented with pixel unshuffle and MLP projection. 属于 Core 神经网络/数学辅助(共享张量变换)。

参数

img_sizeUnion[int, tuple[int, int]]默认值 224
patch_sizeUnion[int, tuple[int, int]]默认值 16
in_chansint默认值 3
embed_dimint默认值 768
norm_layerOptional[Callable[..., nn.Module]]默认值 None
flatten_embeddingbool默认值 True
class PatchGridSpec(original_shape: tuple[int, ...],patch_size: tuple[int, int],layout: ImageLayout = 'nchw')
worldfoundry.corefrom worldfoundry.core import PatchGridSpec

PatchGridSpec — Shape contract needed to invert a 2D image patchification. 属于 Core 神经网络/数学辅助(共享张量变换)。

属性

original_shapetuple[int, ...]
patch_sizetuple[int, int]
layoutImageLayout默认值 'nchw'

方法

propbatch_shape -> tuple[int, ...]源码

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

参数

self

返回值

tuple[int, ...]
propchannels -> int源码

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

参数

self

返回值

int
propspatial_shape -> tuple[int, int]源码

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

参数

self

返回值

tuple[int, int]
propgrid_shape -> tuple[int, int]源码

grid_shape — Number of patches along height and width.

参数

self

返回值

tuple[int, int]
proppatch_vector_size -> int源码

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

参数

self

返回值

int
proppatch_count -> int源码

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

参数

self

返回值

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

简介

patchify_image — Convert an image tensor into flattened 2D patch tokens. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:tuple[Any, PatchGridSpec]。

源码 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)`.

参数

valueAny
patch_sizeint | Sequence[int]
layoutImageLayout默认值 'nchw'

返回值

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

Permute — Module wrapper around `Tensor.permute`. 属于 Core 神经网络/数学辅助(共享张量变换)。

属性

dimstuple[int, ...]

方法

methforward(value: Tensor) -> Tensor源码

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

参数

valueTensor

返回值

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

PixelUnshuffle — Module wrapper for `torch.nn.functional.pixel_unshuffle`. 属于 Core 神经网络/数学辅助(共享张量变换)。

参数

downscale_factorint

方法

methforward(value: Tensor) -> Tensor源码

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

参数

valueTensor

返回值

Tensor

异常

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

quaternion_xyzw_to_rotation_matrix — Convert `[..., x, y, z, w] quaternions to rotation matrices. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:Tensor`。

参数

quaternionsTensor

返回值

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

ray_condition — Build per-pixel Plucker ray features from intrinsics and camera-to-world poses. 属于 Core 神经网络/数学辅助(共享张量变换)。

参数

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_flag默认值 None
Optional boolean mask selecting horizontally flipped views.
use_ray_obool默认值 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

rms_norm — Apply RMS normalization over the last dimension. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:Any。

参数

valueAny
weightAny默认值 None
epsfloat默认值 1e-06

返回值

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

rotation_matrix_to_euler_angles_opencv — Return the ZYX angles in OpenCV's `(z, y, x) order. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:tuple[float, float, float]`。

参数

rotationnp.ndarray

返回值

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

rotation_matrix_to_euler_angles_zyx — Convert a 3x3 rotation matrix to `[x, y, z] Euler angles. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:np.ndarray`。

参数

rotationnp.ndarray

返回值

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

rotation_matrix_to_quaternion_wxyz — Convert a 3x3 rotation matrix to a normalized `[w, x, y, z] quaternion. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:np.ndarray`。

参数

rotationnp.ndarray

返回值

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

简介

rotation_matrix_to_quaternion_xyzw — Convert `[..., 3, 3] rotation matrices to canonical XYZW quaternions. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:Tensor`。

源码 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.

参数

matrixTensor

返回值

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

SchedulerInterface — Base interface for diffusion noise schedules. 属于 Core 神经网络/数学辅助(共享张量变换)。

属性

alphas_cumprodtorch.Tensor

方法

methadd_noise(clean_latent: torch.Tensor,noise: torch.Tensor,timestep: torch.Tensor)源码

add_noise — Run the forward corruption process.

参数

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

convert_x0_to_noise — Convert a clean-data prediction to a noise prediction.

参数

x0torch.Tensor
xttorch.Tensor
timesteptorch.Tensor

返回值

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

convert_noise_to_x0 — Convert a noise prediction to a clean-data prediction.

参数

noisetorch.Tensor
xttorch.Tensor
timesteptorch.Tensor

返回值

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

convert_velocity_to_x0 — Convert a velocity prediction to a clean-data prediction.

参数

velocitytorch.Tensor
xttorch.Tensor
timesteptorch.Tensor

返回值

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

split_attention_heads — Reshape `(..., seq, hidden) to (..., heads, seq, head_dim). 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:Any`。

参数

valueAny
num_headsint

返回值

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

standardize_quaternion_xyzw — Choose the equivalent XYZW quaternion whose real part is non-negative. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:Tensor。

参数

quaternionsTensor

返回值

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 前馈层。

参数

in_featuresint
hidden_featuresOptional[int]默认值 None
out_featuresOptional[int]默认值 None
act_layerCallable[..., nn.Module] | None默认值 None
dropfloat默认值 0.0
biasbool默认值 True

方法

methforward(x: Tensor) -> Tensor源码

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

参数

xTensor

返回值

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

SwiGLUFFNFused — SwiGLU FFN with hidden width rounded for tensor-core-friendly matmuls. 属于 Core 神经网络/数学辅助(共享张量变换)。

参数

in_featuresint
Input width.
hidden_featuresOptional[int]默认值 None
Requested hidden width before the SwiGLU 2/3 adjustment and upward rounding to a multiple of eight.
out_featuresOptional[int]默认值 None
Output width; defaults to `in_features`.
act_layerCallable[..., nn.Module] | None默认值 None
Accepted for MLP-constructor compatibility; unused.
dropfloat默认值 0.0
Accepted for MLP-constructor compatibility; unused.
biasbool默认值 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

transformer_shape_spec — Build a reusable shape spec for attention and MLP dimensions. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:TransformerShapeSpec。

参数

hidden_sizeint
num_headsint
mlp_ratiofloat默认值 4.0
multiple_ofint | None默认值 None
class TransformerShapeSpec(hidden_size: int,num_heads: int,head_dim: int,mlp_hidden_size: int)
worldfoundry.corefrom worldfoundry.core import TransformerShapeSpec

TransformerShapeSpec — Common transformer dimensions derived from hidden size and head count. 属于 Core 神经网络/数学辅助(共享张量变换)。

属性

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

unpatchify_image — Invert `patchify_image using the returned PatchGridSpec. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:Any`。

参数

patchesAny

返回值

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

zero_module — Detach and zero all parameters in a module. 属于 Core 神经网络/数学辅助(共享张量变换)。 标注返回类型:nn.Module。

参数

modulenn.Module

返回值

nn.Module