core.transformer.custom_layers.batch_invariant_kernels#
Module Contents#
Classes#
Autograd function implementing batch-invariant TE GEMM. |
|
Autograd function implementing batch-invariant RMSNorm. |
Functions#
Return whether TE supports explicit FlashAttention version selection. |
|
Require TE’s explicit FlashAttention version selection. |
|
Build launch metadata for Triton matmul kernels used in BIK matmul. |
|
Persistent matmul Triton kernel backing |
|
Returns the number of streaming multiprocessors (SMs) or equivalent compute units for the available accelerator. Assigns the value to NUM_SMS. |
|
Persistent matmul kernel used by batch-invariant GEMM. |
|
Compute log_softmax along the last dimension of a 2D tensor. Each block handles one row of the input tensor. |
|
Compute log_softmax using Triton kernel. |
|
Kernel for computing mean along a single dimension. Input is viewed as (M, N, K) where N is the dimension being reduced. |
|
Triton implementation of torch.mean with single dimension reduction. |
|
|
|
Batch-invariant replacement for |
|
Batch-invariant replacement for |
|
Batch-invariant replacement for |
|
Return the (block_m, block_n) tiling used for batch-invariant attention. |
|
Patch Transformer Engine modules to use batch-invariant GEMM and RMSNorm. |
|
Replace TE.general_grouped_gemm with a batch-invariant dispatcher. |
|
Restore the originals captured by _te_patch_general_grouped_gemm. |
|
Decide if TE’s general_grouped_gemm call can be served by DeepGEMM bf16. |
|
Batch-invariant replacement for TE general_grouped_gemm. |
|
Stack a per-expert weight list into a contiguous [E, N, K] buffer. |
|
TE forward: Y = X @ W^T per expert, then optional bias. |
|
TE dgrad: dX = dY @ W per expert. |
|
TE wgrad: dW[g] = dY[g]^T @ X[g], plus optional dbias[g] = sum(dY[g], dim=0). |
|
Restore original Transformer Engine functions if they were patched. |
|
Utility to parse TE general_gemm flexible signature. |
|
Batch-invariant replacement for TE’s fused-module |
|
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) |
|
Batch-invariant RMSNorm wrapper that delegates to autograd-aware implementation. |
|
Raise a clear error if DeepGEMM bf16 grouped bindings are unavailable. |
|
Convert inclusive cumulative per-expert offsets to per-row expert ids. |
|
Convert TE per-expert token counts (List[int]) to int32 [m_total] m_indices. |
|
Lazily fetch DeepGEMM’s required per-expert block alignment. |
|
Return the M alignment required by the DeepGEMM grouped-GEMM backend. |
|
Pad an M-grouped contiguous input to satisfy DeepGEMM’s per-expert M alignment. |
|
bf16 M-grouped GEMM via DeepGEMM. Deterministic / batch-invariant. |
|
DeepGEMM M-grouped GEMM for already aligned expert blocks. |
|
K-grouped TN GEMM producing per-expert weight gradients via DeepGEMM. |
|
Run the graph-safe grouped GEMM over pre-aligned inference expert blocks. |
|
Patched TE RMSNorm.forward that routes to batch-invariant implementation with autograd support. |
|
Return True if global batch-invariant mode is currently enabled. |
|
Whether TE device-metadata GEMM has been validated on this GPU/library pair. |
|
Keep TE’s required full workspace only on the validated grouped-GEMM path. |
|
Make the NATIVE cuBLASLt GEMM kernels batch-invariant via workspace starvation. |
|
Restore the TE workspace function and env pinned by the te_native backend. |
|
Return the active batch-invariant cross-rank combine collective. |
|
Return the active batch-invariant GEMM backend name. |
|
Enable global batch-invariant mode and patch Aten/TE kernels. |
|
Disable global batch-invariant mode and restore original kernels. |
|
Pin the Mamba chunked-scan forward kernels to fixed tile configs. |
|
Restore the original autotune config lists saved by _pin_mamba_autotuners. |
|
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],
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,
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 @ bvia DeepGEMMbf16_gemm_nn. Both inputs are row-major.Bitwise-identical to
torch.mmon 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.dimover 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],
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.FunctionAutograd 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
layoutsemantics, flattens leading dimensions of the input as needed, applies optional bias, and casts toout_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:muis None for RMSNorm andrsigmais 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.FunctionAutograd 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
xusing an RMSNorm-style statistic computed viamean_dim, applies affineweight, 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,
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,
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],
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,
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],
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,
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,
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,
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::addmmthrough. “te_native” (default) keeps the native cuBLASLt kernels and obtains invariance via workspace starvation. “deepgemm” routes bf16 CUDA inputs through DeepGEMMbf16_gemm_nn. “triton” routes through the batch-invariant Tritonmatmul_persistentkernel (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
enabledis 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.