core.transformer.custom_layers.batch_invariant_kernels#

Module Contents#

Classes#

BatchInvariantTEGemmFn

Autograd function implementing batch-invariant TE GEMM.

BatchInvariantRMSNormFn

Autograd function implementing batch-invariant RMSNorm.

Functions#

te_supports_batch_invariant_attention

Return whether TE supports explicit FlashAttention version selection.

assert_te_supports_batch_invariant_attention

Require TE’s explicit FlashAttention version selection.

_matmul_launch_metadata

Build launch metadata for Triton matmul kernels used in BIK matmul.

_compute_pid

matmul_kernel_persistent

Persistent matmul Triton kernel backing matmul_persistent.

get_compute_units

Returns the number of streaming multiprocessors (SMs) or equivalent compute units for the available accelerator. Assigns the value to NUM_SMS.

matmul_persistent

Persistent matmul kernel used by batch-invariant GEMM.

_log_softmax_kernel

Compute log_softmax along the last dimension of a 2D tensor. Each block handles one row of the input tensor.

log_softmax

Compute log_softmax using Triton kernel.

mean_kernel

Kernel for computing mean along a single dimension. Input is viewed as (M, N, K) where N is the dimension being reduced.

mean_dim

Triton implementation of torch.mean with single dimension reduction.

_mm_deepgemm

a @ b via DeepGEMM bf16_gemm_nn. Both inputs are row-major.

mm_batch_invariant

Batch-invariant replacement for aten::mm.

addmm_batch_invariant

Batch-invariant replacement for aten::addmm.

_log_softmax_batch_invariant

mean_batch_invariant

Batch-invariant replacement for aten::mean.dim over one or more dimensions.

get_batch_invariant_attention_block_size

Return the (block_m, block_n) tiling used for batch-invariant attention.

_import_module_if_available

_te_patch_for_batch_invariant

Patch Transformer Engine modules to use batch-invariant GEMM and RMSNorm.

_te_patch_general_grouped_gemm

Replace TE.general_grouped_gemm with a batch-invariant dispatcher.

_te_unpatch_general_grouped_gemm

Restore the originals captured by _te_patch_general_grouped_gemm.

_is_bf16_grouped_path

Decide if TE’s general_grouped_gemm call can be served by DeepGEMM bf16.

_te_general_grouped_gemm_patched

Batch-invariant replacement for TE general_grouped_gemm.

_stack_weights_for_deepgemm

Stack a per-expert weight list into a contiguous [E, N, K] buffer.

_batch_invariant_te_grouped_forward

TE forward: Y = X @ W^T per expert, then optional bias.

_batch_invariant_te_grouped_dgrad

TE dgrad: dX = dY @ W per expert.

_batch_invariant_te_grouped_wgrad

TE wgrad: dW[g] = dY[g]^T @ X[g], plus optional dbias[g] = sum(dY[g], dim=0).

_te_unpatch_for_batch_invariant

Restore original Transformer Engine functions if they were patched.

_extract_te_gemm_args

Utility to parse TE general_gemm flexible signature.

_is_supported_dtype_for_bik

_te_apply_normalization_patched

Batch-invariant replacement for TE’s fused-module apply_normalization.

_te_general_gemm_patched

Batch-invariant replacement for TE general_gemm. Returns a list of tensors to match TE’s API: (gemm_out, bias_grad, gelu_input, extra_output)

rmsnorm_batch_invariant

Batch-invariant RMSNorm wrapper that delegates to autograd-aware implementation.

_require_deepgemm_bf16

Raise a clear error if DeepGEMM bf16 grouped bindings are unavailable.

_offs_to_m_indices

Convert inclusive cumulative per-expert offsets to per-row expert ids.

_m_splits_to_m_indices

Convert TE per-expert token counts (List[int]) to int32 [m_total] m_indices.

_deepgemm_m_alignment

Lazily fetch DeepGEMM’s required per-expert block alignment.

grouped_gemm_batch_invariant_alignment

Return the M alignment required by the DeepGEMM grouped-GEMM backend.

_pad_for_m_grouped

Pad an M-grouped contiguous input to satisfy DeepGEMM’s per-expert M alignment.

_bf16_grouped_gemm_contiguous

bf16 M-grouped GEMM via DeepGEMM. Deterministic / batch-invariant.

_bf16_grouped_gemm_aligned_contiguous

DeepGEMM M-grouped GEMM for already aligned expert blocks.

_bf16_grouped_gemm_wgrad_contiguous

K-grouped TN GEMM producing per-expert weight gradients via DeepGEMM.

grouped_gemm_batch_invariant

Run the graph-safe grouped GEMM over pre-aligned inference expert blocks.

_te_rmsnorm_forward_patched

Patched TE RMSNorm.forward that routes to batch-invariant implementation with autograd support.

is_batch_invariant_mode_enabled

Return True if global batch-invariant mode is currently enabled.

te_supports_batch_invariant_grouped_gemm

Whether TE device-metadata GEMM has been validated on this GPU/library pair.

_get_te_native_grouped_workspace

Keep TE’s required full workspace only on the validated grouped-GEMM path.

_enable_te_native_workspace_starvation

Make the NATIVE cuBLASLt GEMM kernels batch-invariant via workspace starvation.

_disable_te_native_workspace_starvation

Restore the TE workspace function and env pinned by the te_native backend.

get_batch_invariant_collective

Return the active batch-invariant cross-rank combine collective.

get_batch_invariant_backend

Return the active batch-invariant GEMM backend name.

enable_batch_invariant_mode

Enable global batch-invariant mode and patch Aten/TE kernels.

disable_batch_invariant_mode

Disable global batch-invariant mode and restore original kernels.

_pin_mamba_autotuners

Pin the Mamba chunked-scan forward kernels to fixed tile configs.

_unpin_mamba_autotuners

Restore the original autotune config lists saved by _pin_mamba_autotuners.

set_batch_invariant_mode

Context manager to toggle global batch-invariant mode.

Data#

API#

core.transformer.custom_layers.batch_invariant_kernels.__all__#

[‘set_batch_invariant_mode’, ‘is_batch_invariant_mode_enabled’, ‘disable_batch_invariant_mode’, ‘ena…

core.transformer.custom_layers.batch_invariant_kernels._LOGGER#

‘getLogger(…)’

core.transformer.custom_layers.batch_invariant_kernels._TE_BATCH_INVARIANT_COMMIT#

‘cb4a45fd’

core.transformer.custom_layers.batch_invariant_kernels._TE_BATCH_INVARIANT_MIN_VERSION#

‘Version(…)’

core.transformer.custom_layers.batch_invariant_kernels.te_supports_batch_invariant_attention() → bool#

Return whether TE supports explicit FlashAttention version selection.

core.transformer.custom_layers.batch_invariant_kernels.assert_te_supports_batch_invariant_attention() → None#

Require TE’s explicit FlashAttention version selection.

core.transformer.custom_layers.batch_invariant_kernels._matmul_launch_metadata(
grid: collections.abc.Callable[..., Any],
kernel: Any,
args: Dict[str, Any],
) → Dict[str, Any]#

Build launch metadata for Triton matmul kernels used in BIK matmul.

core.transformer.custom_layers.batch_invariant_kernels._compute_pid(
tile_id,
num_pid_in_group,
num_pid_m,
GROUP_SIZE_M,
NUM_SMS,
)#
core.transformer.custom_layers.batch_invariant_kernels.matmul_kernel_persistent(
a_ptr,
b_ptr,
c_ptr,
bias_ptr,
M,
N,
K,
stride_am,
stride_ak,
stride_bk,
stride_bn,
stride_cm,
stride_cn,
BLOCK_SIZE_M: triton.language.constexpr,
BLOCK_SIZE_N: triton.language.constexpr,
BLOCK_SIZE_K: triton.language.constexpr,
GROUP_SIZE_M: triton.language.constexpr,
NUM_SMS: triton.language.constexpr,
A_LARGE: triton.language.constexpr,
B_LARGE: triton.language.constexpr,
C_LARGE: triton.language.constexpr,
HAS_BIAS: triton.language.constexpr,
)#

Persistent matmul Triton kernel backing matmul_persistent.

core.transformer.custom_layers.batch_invariant_kernels.get_compute_units()#

Returns the number of streaming multiprocessors (SMs) or equivalent compute units for the available accelerator. Assigns the value to NUM_SMS.

core.transformer.custom_layers.batch_invariant_kernels.matmul_persistent(
a: torch.Tensor,
b: torch.Tensor,
bias: torch.Tensor | None = None,
)#

Persistent matmul kernel used by batch-invariant GEMM.

core.transformer.custom_layers.batch_invariant_kernels._log_softmax_kernel(
input_ptr,
output_ptr,
input_row_stride,
output_row_stride,
n_cols,
BLOCK_SIZE: triton.language.constexpr,
)#

Compute log_softmax along the last dimension of a 2D tensor. Each block handles one row of the input tensor.

core.transformer.custom_layers.batch_invariant_kernels.log_softmax(input: torch.Tensor, dim: int = -1) → torch.Tensor#

Compute log_softmax using Triton kernel.

Parameters:
  • input – Input tensor

  • dim – Dimension along which to compute log_softmax (only -1 or last dim supported)

Returns:

Tensor with log_softmax applied along the specified dimension

core.transformer.custom_layers.batch_invariant_kernels.mean_kernel(
input_ptr,
output_ptr,
input_stride0,
input_stride1,
input_stride2,
output_stride0,
output_stride1,
M,
N,
K,
BLOCK_SIZE: triton.language.constexpr,
)#

Kernel for computing mean along a single dimension. Input is viewed as (M, N, K) where N is the dimension being reduced.

core.transformer.custom_layers.batch_invariant_kernels.mean_dim(
input: torch.Tensor,
dim: int,
keepdim: bool = False,
dtype: torch.dtype | None = None,
) → torch.Tensor#

Triton implementation of torch.mean with single dimension reduction.

Parameters:
  • input – Input tensor

  • dim – Single dimension along which to compute mean

  • keepdim – Whether to keep the reduced dimension

  • dtype – Output dtype. If None, uses input dtype (or float32 for integer inputs)

Returns:

Tensor with mean values along specified dimension

core.transformer.custom_layers.batch_invariant_kernels._BATCH_INVARIANT_BACKENDS#

(‘deepgemm’, ‘triton’, ‘te_native’)

core.transformer.custom_layers.batch_invariant_kernels._BATCH_INVARIANT_BACKEND: str#

‘deepgemm’

core.transformer.custom_layers.batch_invariant_kernels._mm_deepgemm(a: torch.Tensor, b: torch.Tensor) → torch.Tensor#

a @ b via DeepGEMM bf16_gemm_nn. Both inputs are row-major.

Bitwise-identical to torch.mm on Hopper/Blackwell, deterministic across runs, batch-invariant.

core.transformer.custom_layers.batch_invariant_kernels.mm_batch_invariant(a, b)#

Batch-invariant replacement for aten::mm.

core.transformer.custom_layers.batch_invariant_kernels.addmm_batch_invariant(bias, a, b)#

Batch-invariant replacement for aten::addmm.

core.transformer.custom_layers.batch_invariant_kernels._log_softmax_batch_invariant(input, dim, _half_to_float)#
core.transformer.custom_layers.batch_invariant_kernels.mean_batch_invariant(
input,
dim,
keepdim=False,
dtype: torch.dtype | None = None,
)#

Batch-invariant replacement for aten::mean.dim over one or more dimensions.

core.transformer.custom_layers.batch_invariant_kernels.AttentionBlockSize#

‘namedtuple(…)’

core.transformer.custom_layers.batch_invariant_kernels.get_batch_invariant_attention_block_size() → core.transformer.custom_layers.batch_invariant_kernels.AttentionBlockSize#

Return the (block_m, block_n) tiling used for batch-invariant attention.

core.transformer.custom_layers.batch_invariant_kernels._batch_invariant_MODE#

False

core.transformer.custom_layers.batch_invariant_kernels._batch_invariant_LIB#

None

core.transformer.custom_layers.batch_invariant_kernels._TE_GENERAL_GEMM_ORIG#

None

core.transformer.custom_layers.batch_invariant_kernels._TE_RMSNORM_ORIG_FWD#

None

core.transformer.custom_layers.batch_invariant_kernels._MEG_TE_GENERAL_GEMM_ORIG#

None

core.transformer.custom_layers.batch_invariant_kernels._TE_RMSNORM_FUNC_ORIGS: Dict[str, Any]#

None

core.transformer.custom_layers.batch_invariant_kernels._TE_GEMM_FUNC_ORIGS: Dict[str, Any]#

None

core.transformer.custom_layers.batch_invariant_kernels._TE_GROUPED_GEMM_FUNC_ORIGS: Dict[str, Any]#

None

core.transformer.custom_layers.batch_invariant_kernels._TE_APPLY_NORM_ORIGS: Dict[str, Any]#

None

core.transformer.custom_layers.batch_invariant_kernels._import_module_if_available(name: str)#
core.transformer.custom_layers.batch_invariant_kernels._te_patch_for_batch_invariant(
skip_gemm: bool = False,
skip_rmsnorm: bool = False,
)#

Patch Transformer Engine modules to use batch-invariant GEMM and RMSNorm.

This monkey-patches TE’s GEMM and RMSNorm entry points to dispatch to the batch-invariant implementations when batch-invariant mode is enabled. Safe no-op if TE is unavailable.

Parameters:
  • skip_gemm – leave TE’s native GEMMs (general_gemm and grouped GEMM) in place (used by the “te_native” backend, where GEMM batch invariance comes from cuBLASLt workspace starvation rather than kernel substitution).

  • skip_rmsnorm – leave TE’s native normalization in place (RMSNorm class/module functions and the fused-module apply_normalization entry). Used by “te_native”, where the norm’s M%32 reduction bit-class is held constant by the 64-multiple alignment discipline instead of kernel substitution.

core.transformer.custom_layers.batch_invariant_kernels._te_patch_general_grouped_gemm() → None#

Replace TE.general_grouped_gemm with a batch-invariant dispatcher.

Patches the symbol at three import sites — the consumer module (transformer_engine.pytorch.module.grouped_linear), the package-level re-export (transformer_engine.pytorch.cpp_extensions), and the source module (transformer_engine.pytorch.cpp_extensions.gemm). Stores originals in _TE_GROUPED_GEMM_FUNC_ORIGS so the unpatch can restore them.

core.transformer.custom_layers.batch_invariant_kernels._te_unpatch_general_grouped_gemm() → None#

Restore the originals captured by _te_patch_general_grouped_gemm.

core.transformer.custom_layers.batch_invariant_kernels._is_bf16_grouped_path(A, B, quantization_params, gelu: bool) → bool#

Decide if TE’s general_grouped_gemm call can be served by DeepGEMM bf16.

core.transformer.custom_layers.batch_invariant_kernels._te_general_grouped_gemm_patched(
A,
B,
out,
quantization_params=None,
out_dtype=None,
layout: str = 'TN',
m_splits=None,
gelu: bool = False,
grad: bool = False,
accumulate: bool = False,
bias=None,
use_bias: bool = False,
use_split_accumulator: bool = False,
D_dtype=None,
single_output: bool = False,
)#

Batch-invariant replacement for TE general_grouped_gemm.

Dispatches by (layout, single_output, grad) to forward / dgrad / wgrad implementations backed by DeepGEMM. Unsupported calls fail rather than silently using a kernel that is not guaranteed batch invariant.

core.transformer.custom_layers.batch_invariant_kernels._stack_weights_for_deepgemm(
weights: List[torch.Tensor],
) → torch.Tensor#

Stack a per-expert weight list into a contiguous [E, N, K] buffer.

core.transformer.custom_layers.batch_invariant_kernels._batch_invariant_te_grouped_forward(
A,
B,
out,
m_splits,
bias,
use_bias,
accumulate,
)#

TE forward: Y = X @ W^T per expert, then optional bias.

A = weights: List[Tensor[N, K]] B = inputmats: List[Tensor[m_i, K]] out: [single Tensor[M_total, N]] (single_output=True)

core.transformer.custom_layers.batch_invariant_kernels._batch_invariant_te_grouped_dgrad(A, B, out, m_splits, accumulate)#

TE dgrad: dX = dY @ W per expert.

A = weights: List[Tensor[N, K]] B = grad_y_per_expert: List[Tensor[m_i, N]] out: [single Tensor[M_total, K]] (single_output=True)

core.transformer.custom_layers.batch_invariant_kernels._batch_invariant_te_grouped_wgrad(
A,
B,
out,
m_splits,
use_bias,
accumulate,
)#

TE wgrad: dW[g] = dY[g]^T @ X[g], plus optional dbias[g] = sum(dY[g], dim=0).

A = inputmats: List[Tensor[m_i, K]] B = grad_y: List[Tensor[m_i, N]] out: List[Tensor[N, K]] per expert (single_output=False)

core.transformer.custom_layers.batch_invariant_kernels._te_unpatch_for_batch_invariant()#

Restore original Transformer Engine functions if they were patched.

core.transformer.custom_layers.batch_invariant_kernels._extract_te_gemm_args(
args: tuple,
kwargs: Dict[str, Any],
)#

Utility to parse TE general_gemm flexible signature.

Returns (A, B, out_dtype, layout, out, bias, grad).

core.transformer.custom_layers.batch_invariant_kernels._is_supported_dtype_for_bik(t: torch.dtype) → bool#
class core.transformer.custom_layers.batch_invariant_kernels.BatchInvariantTEGemmFn#

Bases: torch.autograd.Function

Autograd function implementing batch-invariant TE GEMM.

static forward(
ctx,
A: torch.Tensor,
B: torch.Tensor,
bias: Optional[torch.Tensor],
out_dtype: Optional[torch.dtype],
layout: str,
)#

Forward pass computing batch-invariant TE GEMM.

Respects TE’s flexible layout semantics, flattens leading dimensions of the input as needed, applies optional bias, and casts to out_dtype.

static backward(ctx, grad_output: torch.Tensor)#

Backward pass for batch-invariant TE GEMM.

Computes gradients w.r.t. A, B, and optional bias while mirroring the reshaping/layout logic used in the forward pass.

core.transformer.custom_layers.batch_invariant_kernels._te_apply_normalization_patched(
inputmat,
ln_out,
ln_weight,
ln_bias,
eps,
output_quantizer,
output_dtype,
normalization,
fwd_ln_sm_margin,
zero_centered_gamma,
)#

Batch-invariant replacement for TE’s fused-module apply_normalization.

Routes RMSNorm through the batch-invariant implementation (fp32 stats via mean_dim, deterministic within-row reduction independent of row count). Falls back to the original TE kernel for configurations the BI path does not cover (LayerNorm, fp8 quantized output).

Returns (ln_out, mu, rsigma) like TE: mu is None for RMSNorm and rsigma is fp32 with shape [rows], which TE’s rmsnorm backward consumes.

core.transformer.custom_layers.batch_invariant_kernels._te_general_gemm_patched(*args, **kwargs) → List[torch.Tensor]#

Batch-invariant replacement for TE general_gemm. Returns a list of tensors to match TE’s API: (gemm_out, bias_grad, gelu_input, extra_output)

class core.transformer.custom_layers.batch_invariant_kernels.BatchInvariantRMSNormFn#

Bases: torch.autograd.Function

Autograd function implementing batch-invariant RMSNorm.

static forward(
ctx,
x: torch.Tensor,
weight: torch.Tensor,
eps: float,
zero_centered_gamma: bool,
)#

Forward pass for batch-invariant RMSNorm.

Normalizes x using an RMSNorm-style statistic computed via mean_dim, applies affine weight, and stores intermediate rsigma for backward.

static backward(ctx, grad_output: torch.Tensor)#

Backward pass for batch-invariant RMSNorm.

Computes gradients w.r.t. input and weight while matching TE’s fp32 accumulation and reduction behavior for numerical stability.

core.transformer.custom_layers.batch_invariant_kernels.rmsnorm_batch_invariant(
x: torch.Tensor,
weight: torch.Tensor,
eps: float,
) → torch.Tensor#

Batch-invariant RMSNorm wrapper that delegates to autograd-aware implementation.

This provides a simple functional interface while using the optimized BatchInvariantRMSNormFn which has better numerics (fp32 precision in forward/backward).

core.transformer.custom_layers.batch_invariant_kernels._require_deepgemm_bf16(op: str) → None#

Raise a clear error if DeepGEMM bf16 grouped bindings are unavailable.

core.transformer.custom_layers.batch_invariant_kernels._offs_to_m_indices(offs: torch.Tensor, m_total: int) → torch.Tensor#

Convert inclusive cumulative per-expert offsets to per-row expert ids.

offs: int32 [num_experts] inclusive offsets — offs[i] is the (exclusive) end row of expert i in the contiguous M dimension. Equivalently, offs[i] is the start of expert i+1. Returns: int32 [m_total] m_indices[r] = expert id for row r. Rows past offs[-1] (post-padding tail when m_total > offs[-1]) get -1; DeepGEMM skips those rows.

core.transformer.custom_layers.batch_invariant_kernels._m_splits_to_m_indices(
m_splits: List[int],
device: torch.device,
m_total: int,
) → torch.Tensor#

Convert TE per-expert token counts (List[int]) to int32 [m_total] m_indices.

No padding rows in TE training path — sum(m_splits) == m_total exactly.

core.transformer.custom_layers.batch_invariant_kernels._DEEPGEMM_M_ALIGNMENT: Optional[int]#

None

core.transformer.custom_layers.batch_invariant_kernels._deepgemm_m_alignment() → int#

Lazily fetch DeepGEMM’s required per-expert block alignment.

core.transformer.custom_layers.batch_invariant_kernels.grouped_gemm_batch_invariant_alignment() → int#

Return the M alignment required by the DeepGEMM grouped-GEMM backend.

core.transformer.custom_layers.batch_invariant_kernels._pad_for_m_grouped(a: torch.Tensor, counts: List[int]) → tuple#

Pad an M-grouped contiguous input to satisfy DeepGEMM’s per-expert M alignment.

Returns the padded input, row-to-expert map, and padded counts. The padded layout groups expert i’s true rows contiguously at the start of its 128-aligned block; remaining rows in the block are zero with m_indices=-1.

core.transformer.custom_layers.batch_invariant_kernels._bf16_grouped_gemm_contiguous(
a: torch.Tensor,
b: torch.Tensor,
m_indices: torch.Tensor,
counts: List[int],
) → torch.Tensor#

bf16 M-grouped GEMM via DeepGEMM. Deterministic / batch-invariant.

a: [M_total, K] bf16, contiguous, expert-grouped (rows of expert i are contiguous; m_indices is sorted). b: [E, N, K] bf16, contiguous (per-expert weights, NT layout — DeepGEMM transposes B internally). m_indices: [M_total] int32, expert id per row (-1 to skip). Returns: [M_total, N] bf16 with rows in the same order as a.

Handles DeepGEMM’s per-expert M alignment requirement by padding/unpadding internally; the caller does not need pre-padded inputs.

core.transformer.custom_layers.batch_invariant_kernels._bf16_grouped_gemm_aligned_contiguous(
a: torch.Tensor,
b: torch.Tensor,
m_indices: torch.Tensor,
) → torch.Tensor#

DeepGEMM M-grouped GEMM for already aligned expert blocks.

This path is used by inference CUDA graphs. The caller is responsible for using grouped_gemm_batch_invariant_alignment() when building expert offsets, so no device-to-host count extraction or dynamic padding is needed on the captured path.

core.transformer.custom_layers.batch_invariant_kernels._bf16_grouped_gemm_wgrad_contiguous(
grad_y: torch.Tensor,
x: torch.Tensor,
counts: List[int],
) → torch.Tensor#

K-grouped TN GEMM producing per-expert weight gradients via DeepGEMM.

grad_y: [M_total, N] bf16, contiguous, expert-grouped. x: [M_total, K] bf16, contiguous, expert-grouped (same row ordering). Returns: [E, N, K] bf16 stacked per-expert wgrad.

DeepGEMM’s k_grouped_bf16 kernel computes in fp32 and requires fp32 d/c accumulators; we cast the result back to bf16. Per-expert K alignment is handled by padding internally.

core.transformer.custom_layers.batch_invariant_kernels.grouped_gemm_batch_invariant(
a: torch.Tensor,
b: torch.Tensor,
*,
offs: torch.Tensor,
m_total: int,
) → torch.Tensor#

Run the graph-safe grouped GEMM over pre-aligned inference expert blocks.

core.transformer.custom_layers.batch_invariant_kernels._te_rmsnorm_forward_patched(self, x: torch.Tensor) → torch.Tensor#

Patched TE RMSNorm.forward that routes to batch-invariant implementation with autograd support.

core.transformer.custom_layers.batch_invariant_kernels.is_batch_invariant_mode_enabled()#

Return True if global batch-invariant mode is currently enabled.

core.transformer.custom_layers.batch_invariant_kernels._TE_NATIVE_WORKSPACE_BYTES#

1024

core.transformer.custom_layers.batch_invariant_kernels._TE_WORKSPACE_SIZE_FN_ORIG#

None

core.transformer.custom_layers.batch_invariant_kernels._TE_GROUPED_WORKSPACE_FN_ORIG#

None

core.transformer.custom_layers.batch_invariant_kernels._TE_NATIVE_ENV_ORIG: dict#

None

core.transformer.custom_layers.batch_invariant_kernels.te_supports_batch_invariant_grouped_gemm(
device: int | None = None,
) → bool#

Whether TE device-metadata GEMM has been validated on this GPU/library pair.

This path cannot use workspace starvation. Keep the numerical validation boundary explicit; 256-row expert padding alone does not guarantee invariance.

core.transformer.custom_layers.batch_invariant_kernels._get_te_native_grouped_workspace(
device: int,
layout: str,
) → torch.Tensor#

Keep TE’s required full workspace only on the validated grouped-GEMM path.

core.transformer.custom_layers.batch_invariant_kernels._enable_te_native_workspace_starvation(
workspace_bytes: int = _TE_NATIVE_WORKSPACE_BYTES,
)#

Make the NATIVE cuBLASLt GEMM kernels batch-invariant via workspace starvation.

cuBLASLt selects split-K reduction variants per M (the co-batch token count), which changes the fp32 accumulation order across batch compositions. Split-K variants require workspace; starving the workspace to ~1KB disqualifies them, pinning every M to the same serial-K reduction recipe — batch-invariant at native kernel speed, with no kernel substitution. (Tile shape selection may still vary with M, but M/N tiling does not affect bits: bf16 products are exact in fp32, so only the K-reduction order matters.)

Two knobs must both land:

  • cuBLASLt env pins for kernels that honor them (set before first use).

  • Transformer Engine’s own workspace: TE (<= 2.15 verified) hardcodes 32MiB in get_cublas_workspace_size_bytes() and ignores CUBLASLT_WORKSPACE_SIZE, so the env pin alone never engages for TE-launched GEMMs — patch the size fn and clear its lru_cache.

core.transformer.custom_layers.batch_invariant_kernels._disable_te_native_workspace_starvation()#

Restore the TE workspace function and env pinned by the te_native backend.

core.transformer.custom_layers.batch_invariant_kernels._BATCH_INVARIANT_COLLECTIVE#

‘ordered’

core.transformer.custom_layers.batch_invariant_kernels.get_batch_invariant_collective() → str#

Return the active batch-invariant cross-rank combine collective.

core.transformer.custom_layers.batch_invariant_kernels.get_batch_invariant_backend() → str#

Return the active batch-invariant GEMM backend name.

core.transformer.custom_layers.batch_invariant_kernels.enable_batch_invariant_mode(
backend: str = 'te_native',
collective: str = 'ordered',
)#

Enable global batch-invariant mode and patch Aten/TE kernels.

Parameters:

backend – which kernel to dispatch aten::mm/aten::addmm through. “te_native” (default) keeps the native cuBLASLt kernels and obtains invariance via workspace starvation. “deepgemm” routes bf16 CUDA inputs through DeepGEMM bf16_gemm_nn. “triton” routes through the batch-invariant Triton matmul_persistent kernel (works for bf16/fp16/fp32 and on any CUDA device). “te_native” keeps the native cuBLASLt kernels (aten and TE) and obtains invariance via workspace starvation instead of kernel substitution. Grouped GEMM uses DeepGEMM for “deepgemm”/”triton”; “te_native” leaves it native.

core.transformer.custom_layers.batch_invariant_kernels.disable_batch_invariant_mode()#

Disable global batch-invariant mode and restore original kernels.

core.transformer.custom_layers.batch_invariant_kernels._PINNED_AUTOTUNERS: list#

[]

core.transformer.custom_layers.batch_invariant_kernels._PINNED_MAMBA_CONFIGS#

None

core.transformer.custom_layers.batch_invariant_kernels._pin_mamba_autotuners()#

Pin the Mamba chunked-scan forward kernels to fixed tile configs.

BLOCK sizes determine the fp32 reduction grouping inside tl.dot loops, so rollout/train parity needs the inference process (repo ssd_* kernels) and the training process (mamba_ssm package kernels) to pick the same config. Triton’s autotuner re-benchmarks per process and timing noise can flip the winner; we’ve seen that break parity in practice. Pinning both sides to the same config removes the benchmark from the loop.

Only the five forward kernels matter for parity; backward kernels only affect gradients.

core.transformer.custom_layers.batch_invariant_kernels._unpin_mamba_autotuners()#

Restore the original autotune config lists saved by _pin_mamba_autotuners.

core.transformer.custom_layers.batch_invariant_kernels.set_batch_invariant_mode(
enabled: bool = True,
backend: Optional[str] = None,
)#

Context manager to toggle global batch-invariant mode.

When enabled is True, batch-invariant kernels are enabled for the duration of the context; when False, they are disabled for the duration. This implementation is re-entrant and correctly restores the previous state even under nesting. The helper default remains “triton” for tests that exercise non-bf16 operators.