Skip to navigation

nemo_automodel.components.models.ergo.kernels

View as MarkdownOpen in Claude

Kernels for Ergo’s elementwise chains: ReLU squared, RMSNorm and the residual blend.

An Ergo block spends more time in these chains than in its matrix products when they run as separate PyTorch operators: every cast, multiply and reduction is one pass over a [tokens, hidden] tensor (hidden is 8192, and the routed experts’ outputs hold eight rows per token), and autograd keeps FP32 copies of the intermediates for the backward.

A chain that a library kernel computes uses it: Transformer Engine’s squared ReLU (common/squared_relu.py), and QuACK’s RMSNorm for the per-head Q/K normalization. Three chains have no library kernel and get Triton kernels here: the per-expert output RMSNorm, where every row takes the scale of its expert and the row groups stay on the device, the shared expert’s RMSNorm plus the routed output, and the branch RMSNorm plus the residual blend. Each Triton kernel reads its inputs once or twice and writes one output; each backward is the analytic gradient of the whole chain and saves the chain’s inputs and one FP32 inverse RMS per row.

The arithmetic is that of the eager modules in layers.py, including every rounding to the compute dtype between two steps (noted per function). Sums over a row or a column are accumulated in a different order than PyTorch’s reductions, so results agree with the eager chain to FP32 rounding of those sums, not bit for bit.

Module Contents

Classes

NameDescription
_NormResidualbeta * rms_norm(branch) + alpha * residual in FP32.
_RMSNormWeighted RMSNorm with the optional grouped scale and addend of rms_norm.

Functions

NameDescription
_block_shapeReturn rows and columns of one tile: the columns cover a row of width in power-of-two steps.
_norm_residual_bwd_kernelWrite the branch and residual gradients of _norm_residual_fwd_kernel.
_norm_residual_coefficient_grad_kernelSum the per-column gradients of the scale and the two coefficients over the rows of one chunk.
_norm_residual_fwd_kernelWrite beta * rms_norm(x) + alpha * residual in FP32 for BLOCK_R rows.
_rms_norm_bwd_kernelWrite the input gradient of _rms_norm_fwd_kernel.
_rms_norm_fwd_kernelNormalize BLOCK_R rows, scale them, and optionally add a second tensor.
_rms_norm_weight_grad_kernelSum grad * normalized over the rows of one chunk, per group, for one block of columns.
_row_layoutDescribe x as rows of its last dimension without copying a strided projection slice.
library_rms_normApply a weighted RMSNorm with QuACK’s kernels.
rms_normApply Ergo’s weighted RMSNorm, and optionally an addend, with one kernel per pass.
rms_norm_residualNormalize a branch output in FP32 and blend it into the residual stream with one kernel per pass.

Data

HAVE_TRITON

_MAX_BLOCK_COLUMNS

_NUM_WARPS

_REDUCE_BLOCK_COLUMNS

_REDUCE_BLOCK_ROWS

_REDUCE_CHUNK_ROWS

_TILE_ELEMENTS

API

class nemo_automodel.components.models.ergo.kernels._NormResidual()

Bases: Function

beta * rms_norm(branch) + alpha * residual in FP32.

nemo_automodel.components.models.ergo.kernels._NormResidual.backward(
ctx: torch.autograd.function.FunctionCtx,
grad_output: torch.Tensor
) -> tuple[torch.Tensor | None, torch.Tensor | None, torch.Tensor | None, torch.Tensor | None, torch.Tensor | None, None]
staticmethod

Return the gradients of the branch, the scale, the two coefficients and the residual.

Parameters:

ctx
torch.autograd.function.FunctionCtx

Autograd context holding the forward’s inputs and inverse RMS.

grad_output
torch.Tensor

FP32 upstream gradient with the shape of the output.

Returns: torch.Tensor | None

Gradients of branch (contiguous, its shape and dtype), weight, beta and alpha

nemo_automodel.components.models.ergo.kernels._NormResidual.forward(
ctx: torch.autograd.function.FunctionCtx,
branch: torch.Tensor,
weight: torch.Tensor,
beta: torch.Tensor,
alpha: torch.Tensor,
residual: torch.Tensor,
eps: float
) -> torch.Tensor
staticmethod

Run the forward kernel and save what the required gradients read.

Parameters:

ctx
torch.autograd.function.FunctionCtx

Autograd context.

branch
torch.Tensor

Contiguous CUDA tensor of shape […, width] in the compute dtype.

weight
torch.Tensor

FP32 normalization scale of shape [width].

beta
torch.Tensor

FP32 branch coefficient of shape [width].

alpha
torch.Tensor

FP32 residual coefficient of shape [width].

residual
torch.Tensor

Contiguous FP32 tensor with the shape of branch.

eps
float

Value added to the mean square.

Returns: torch.Tensor

Contiguous FP32 tensor with the shape of branch.

class nemo_automodel.components.models.ergo.kernels._RMSNorm()

Bases: Function

Weighted RMSNorm with the optional grouped scale and addend of rms_norm.

nemo_automodel.components.models.ergo.kernels._RMSNorm.backward(
ctx: torch.autograd.function.FunctionCtx,
grad_output: torch.Tensor
) -> tuple[torch.Tensor | None, torch.Tensor | None, torch.Tensor | None, None, None, None]
staticmethod

Return the gradients of the input, the scale and the addend.

Parameters:

ctx
torch.autograd.function.FunctionCtx

Autograd context holding the forward’s inputs and inverse RMS.

grad_output
torch.Tensor

Upstream gradient with the shape of the output.

Returns: torch.Tensor | None

Gradients of x (contiguous, its shape and dtype), weight (its shape, FP32) and addend

nemo_automodel.components.models.ergo.kernels._RMSNorm.forward(
ctx: torch.autograd.function.FunctionCtx,
x: torch.Tensor,
weight: torch.Tensor,
addend: torch.Tensor | None,
group: torch.Tensor | None,
eps: float,
out_dtype: torch.dtype
) -> torch.Tensor
staticmethod

Run the forward kernel and save the chain’s inputs and the inverse RMS.

Parameters:

ctx
torch.autograd.function.FunctionCtx

Autograd context.

x
torch.Tensor

CUDA tensor of shape […, width]; see rms_norm.

weight
torch.Tensor

FP32 scale of shape [width], or [groups, width] with group.

addend
torch.Tensor | None

Contiguous tensor with the shape and dtype of the output, or None.

group
torch.Tensor | None

Int32 scale row of every input row, shape [rows], or None for one scale.

eps
float

Value added to the mean square.

out_dtype
torch.dtype

Output dtype.

Returns: torch.Tensor

Contiguous tensor with the shape of x in out_dtype.

nemo_automodel.components.models.ergo.kernels._block_shape(
width: int
) -> tuple[int, int]

Return rows and columns of one tile: the columns cover a row of width in power-of-two steps.

nemo_automodel.components.models.ergo.kernels._norm_residual_bwd_kernel(
x_ptr,
weight_ptr,
beta_ptr,
alpha_ptr,
grad_ptr,
rstd_ptr,
grad_x_ptr,
grad_residual_ptr,
rows,
width,
WANT_GRAD_X: tl.constexpr,
BLOCK_R: tl.constexpr,
BLOCK_C: tl.constexpr
)

Write the branch and residual gradients of _norm_residual_fwd_kernel.

Parameters:

x_ptr

Saved contiguous branch output of shape [rows, width].

weight_ptr

FP32 normalization scale of shape [width].

beta_ptr

FP32 branch coefficient of shape [width].

alpha_ptr

FP32 residual coefficient of shape [width].

grad_ptr

Contiguous FP32 upstream gradient of shape [rows, width].

rstd_ptr

FP32 inverse RMS of every row, shape [rows], from the forward.

grad_x_ptr

Contiguous branch gradient of shape [rows, width] in the branch dtype; written only when WANT_GRAD_X.

grad_residual_ptr

Contiguous FP32 residual gradient of shape [rows, width], written here.

rows

Number of rows.

width

Number of columns.

WANT_GRAD_X
tl.constexpr

Compute the branch gradient.

BLOCK_R
tl.constexpr

Rows per program.

BLOCK_C
tl.constexpr

Columns per loop iteration.

nemo_automodel.components.models.ergo.kernels._norm_residual_coefficient_grad_kernel(
x_ptr,
weight_ptr,
residual_ptr,
grad_ptr,
rstd_ptr,
partial_ptr,
rows,
width,
chunks,
HAS_RESIDUAL: tl.constexpr,
CHUNK: tl.constexpr,
BLOCK_R: tl.constexpr,
BLOCK_C: tl.constexpr
)

Sum the per-column gradients of the scale and the two coefficients over the rows of one chunk.

Parameters:

x_ptr

Saved contiguous branch output of shape [rows, width].

weight_ptr

FP32 normalization scale of shape [width].

residual_ptr

Saved contiguous FP32 residual of shape [rows, width]; read only when HAS_RESIDUAL.

grad_ptr

Contiguous FP32 upstream gradient of shape [rows, width].

rstd_ptr

FP32 inverse RMS of every row, shape [rows], from the forward.

partial_ptr

FP32 partial sums of shape [3, chunks, width], written here: grad * x * rstd (the scale’s gradient before the branch coefficient), grad * normalized (the branch coefficient’s gradient) and grad * residual (the residual coefficient’s gradient, only when HAS_RESIDUAL).

rows

Number of rows.

width

Number of columns.

chunks

Number of chunks, the first extent of the program grid.

HAS_RESIDUAL
tl.constexpr

Reduce the residual coefficient’s gradient.

CHUNK
tl.constexpr

Rows per program.

BLOCK_R
tl.constexpr

Rows per loop iteration.

BLOCK_C
tl.constexpr

Columns per program.

nemo_automodel.components.models.ergo.kernels._norm_residual_fwd_kernel(
x_ptr,
weight_ptr,
beta_ptr,
alpha_ptr,
residual_ptr,
out_ptr,
rstd_ptr,
rows,
width,
eps,
BLOCK_R: tl.constexpr,
BLOCK_C: tl.constexpr
)

Write beta * rms_norm(x) + alpha * residual in FP32 for BLOCK_R rows.

Parameters:

x_ptr

Contiguous branch output of shape [rows, width], in the compute dtype.

weight_ptr

FP32 normalization scale of shape [width].

beta_ptr

FP32 branch coefficient of shape [width].

alpha_ptr

FP32 residual coefficient of shape [width].

residual_ptr

Contiguous FP32 residual of shape [rows, width].

out_ptr

Contiguous FP32 output of shape [rows, width].

rstd_ptr

FP32 inverse RMS of every row, shape [rows], written here.

rows

Number of rows.

width

Number of columns.

eps

Value added to the mean square.

BLOCK_R
tl.constexpr

Rows per program.

BLOCK_C
tl.constexpr

Columns per loop iteration.

nemo_automodel.components.models.ergo.kernels._rms_norm_bwd_kernel(
x_ptr,
weight_ptr,
group_ptr,
grad_ptr,
rstd_ptr,
grad_x_ptr,
rows,
width,
inner,
stride_outer,
stride_inner,
stride_weight,
HAS_GROUP: tl.constexpr,
BLOCK_R: tl.constexpr,
BLOCK_C: tl.constexpr
)

Write the input gradient of _rms_norm_fwd_kernel.

The rounding of the forward’s output passes the gradient unchanged, as a cast does in autograd.

Parameters:

x_ptr

Saved input, in the layout of the forward.

weight_ptr

FP32 scale of shape [width] or [groups, width].

group_ptr

Int32 scale row of every input row, shape [rows]; read only when HAS_GROUP.

grad_ptr

Contiguous upstream gradient of shape [rows, width].

rstd_ptr

FP32 inverse RMS of every row, shape [rows], from the forward.

grad_x_ptr

Contiguous input gradient of shape [rows, width], written here.

rows

Number of rows.

width

Number of columns.

inner

Rows per outer index of the input layout.

stride_outer

Input stride between outer indices, in elements.

stride_inner

Input stride between rows of one outer index, in elements.

stride_weight

Row stride of a grouped scale, in elements.

HAS_GROUP
tl.constexpr

The scale has one row per group.

BLOCK_R
tl.constexpr

Rows per program.

BLOCK_C
tl.constexpr

Columns per loop iteration.

nemo_automodel.components.models.ergo.kernels._rms_norm_fwd_kernel(
x_ptr,
weight_ptr,
group_ptr,
addend_ptr,
out_ptr,
rstd_ptr,
rows,
width,
inner,
stride_outer,
stride_inner,
stride_weight,
eps,
HAS_GROUP: tl.constexpr,
HAS_ADDEND: tl.constexpr,
BLOCK_R: tl.constexpr,
BLOCK_C: tl.constexpr
)

Normalize BLOCK_R rows, scale them, and optionally add a second tensor.

Row r of the input starts at element (r // inner) * stride_outer + (r % inner) * stride_inner.

Parameters:

x_ptr

Input rows of width elements with unit column stride.

weight_ptr

FP32 scale of shape [width], or [groups, width] with row stride stride_weight.

group_ptr

Int32 scale row of every input row, shape [rows]; read only when HAS_GROUP.

addend_ptr

Contiguous tensor of shape [rows, width] in the input dtype; read only when HAS_ADDEND.

out_ptr

Contiguous output of shape [rows, width].

rstd_ptr

FP32 inverse RMS of every row, shape [rows], written here.

rows

Number of rows.

width

Number of columns.

inner

Rows per outer index of the input layout.

stride_outer

Input stride between outer indices, in elements.

stride_inner

Input stride between rows of one outer index, in elements.

stride_weight

Row stride of a grouped scale, in elements.

eps

Value added to the mean square.

HAS_GROUP
tl.constexpr

The scale has one row per group.

HAS_ADDEND
tl.constexpr

Round the scaled values to the input dtype and add the second tensor in FP32.

BLOCK_R
tl.constexpr

Rows per program.

BLOCK_C
tl.constexpr

Columns per loop iteration.

nemo_automodel.components.models.ergo.kernels._rms_norm_weight_grad_kernel(
x_ptr,
group_ptr,
grad_ptr,
rstd_ptr,
partial_ptr,
rows,
width,
groups,
inner,
stride_outer,
stride_inner,
HAS_GROUP: tl.constexpr,
CHUNK: tl.constexpr,
BLOCK_R: tl.constexpr,
BLOCK_C: tl.constexpr
)

Sum grad * normalized over the rows of one chunk, per group, for one block of columns.

Rows of one group are contiguous and groups ascend with the row index, so a chunk holds the groups from that of its first row to that of its last; each gets its own pass over the chunk.

Parameters:

x_ptr

Saved input, in the layout of the forward.

group_ptr

Int32 scale row of every input row, shape [rows]; read only when HAS_GROUP.

grad_ptr

Contiguous upstream gradient of shape [rows, width].

rstd_ptr

FP32 inverse RMS of every row, shape [rows], from the forward.

partial_ptr

Zero-initialized FP32 partial sums of shape [chunks, groups, width]; chunk c covers rows c * CHUNK up to (c + 1) * CHUNK, and only its groups are written.

rows

Number of rows.

width

Number of columns.

groups

Number of scale rows.

inner

Rows per outer index of the input layout.

stride_outer

Input stride between outer indices, in elements.

stride_inner

Input stride between rows of one outer index, in elements.

HAS_GROUP
tl.constexpr

The scale has one row per group.

CHUNK
tl.constexpr

Rows per program.

BLOCK_R
tl.constexpr

Rows per loop iteration.

BLOCK_C
tl.constexpr

Columns per program.

nemo_automodel.components.models.ergo.kernels._row_layout(
x: torch.Tensor
) -> tuple[torch.Tensor, int, int, int]

Describe x as rows of its last dimension without copying a strided projection slice.

Parameters:

x
torch.Tensor

Tensor of shape […, width] with at least two dimensions. A slice of a wider projection, viewed as […, heads, width], is read in place.

Returns: torch.Tensor

The tensor to read (x, or a contiguous copy when its strides do not form rows), the number of

nemo_automodel.components.models.ergo.kernels.library_rms_norm(
x: torch.Tensor,
weight: torch.Tensor,
eps: float,
out_dtype: torch.dtype
) -> torch.Tensor

Apply a weighted RMSNorm with QuACK’s kernels.

Computes x * rsqrt(mean(x ** 2) + eps) * weight in FP32 and rounds once to out_dtype.

Parameters:

x
torch.Tensor

CUDA tensor of shape […, width] in FP32 or the compute dtype; a strided view is read in place.

weight
torch.Tensor

FP32 scale of shape [width].

eps
float

Value added to the mean square.

out_dtype
torch.dtype

Dtype of the result.

Returns: torch.Tensor

Tensor with the shape of x in out_dtype.

nemo_automodel.components.models.ergo.kernels.rms_norm(
x: torch.Tensor,
weight: torch.Tensor,
eps: float,
out_dtype: torch.dtype,
group_sizes: torch.Tensor | None = None,
addend: torch.Tensor | None = None
) -> torch.Tensor

Apply Ergo’s weighted RMSNorm, and optionally an addend, with one kernel per pass.

The steps and their roundings follow the eager chains:

  • x * rsqrt(mean(x ** 2) + eps) * weight in FP32, rounded once to out_dtype. This is F.rms_norm of a BF16 input with an FP32 weight, as in ErgoComputeRMSNorm and ErgoExpertOutputNorm.
  • addend: the scaled values are rounded to the compute dtype and added to addend in FP32 (the shared expert added to the routed experts’ sum).

Parameters:

x
torch.Tensor

CUDA tensor of shape […, width] in FP32 or the compute dtype. A […, heads, width] view of a slice of a wider projection is read in place.

weight
torch.Tensor

FP32 scale of shape [width], or [groups, width] with group_sizes.

eps
float

Value added to the mean square.

out_dtype
torch.dtype

Dtype of the result.

group_sizes
torch.Tensor | NoneDefaults to None

Integer tensor of shape [groups] with the rows of x that belong to each row of a grouped weight, in order; their sum is the number of rows. It is read on the device only.

addend
torch.Tensor | NoneDefaults to None

Tensor with the shape of x in out_dtype.

Returns: torch.Tensor

Contiguous tensor with the shape of x in out_dtype.

nemo_automodel.components.models.ergo.kernels.rms_norm_residual(
branch: torch.Tensor,
weight: torch.Tensor,
eps: float,
beta: torch.Tensor,
alpha: torch.Tensor,
residual: torch.Tensor
) -> torch.Tensor

Normalize a branch output in FP32 and blend it into the residual stream with one kernel per pass.

Computes beta * (branch * rsqrt(mean(branch ** 2) + eps) * weight) + alpha * residual in FP32, the chain of ErgoRMSNorm and ErgoResidual.

Parameters:

branch
torch.Tensor

CUDA tensor of shape […, width] in the compute dtype.

weight
torch.Tensor

FP32 normalization scale of shape [width].

eps
float

Value added to the mean square.

beta
torch.Tensor

FP32 branch coefficient of shape [width].

alpha
torch.Tensor

FP32 residual coefficient of shape [width].

residual
torch.Tensor

FP32 tensor with the shape of branch.

Returns: torch.Tensor

Contiguous FP32 tensor with the shape of branch.

nemo_automodel.components.models.ergo.kernels.HAVE_TRITON: bool = bool(_HAVE_TRITON and _HAVE_TRITON_LANGUAGE)
nemo_automodel.components.models.ergo.kernels._MAX_BLOCK_COLUMNS = 512
nemo_automodel.components.models.ergo.kernels._NUM_WARPS = 8
nemo_automodel.components.models.ergo.kernels._REDUCE_BLOCK_COLUMNS = 128
nemo_automodel.components.models.ergo.kernels._REDUCE_BLOCK_ROWS = 16
nemo_automodel.components.models.ergo.kernels._REDUCE_CHUNK_ROWS = 512
nemo_automodel.components.models.ergo.kernels._TILE_ELEMENTS = 2048