nemo_automodel.components.models.deepseek_v4.optimized_kernels
nemo_automodel.components.models.deepseek_v4.optimized_kernels
Optional DeepSeek V4 optimized kernel dispatch.
The torch implementations below are kept as the numerical reference. Optional TileLang-backed paths are sourced from:
- Sinkhorn: imported from DeepSeek TileKernels
tile_kernels.modeling.mhc.ops.sinkhorn_normalize. No TileKernels source is vendored in AutoModel. Upstream source: https://github.com/deepseek-ai/TileKernels/blob/36d9e45d38e204ebb87e6f6e833821eee0482fe5/tile_kernels/modeling/mhc/ops/sinkhorn.py Upstream license: MIT, copyright 2026 DeepSeek. - Sparse attention and indexer: vendored/adapted Miles DeepSeek V4 ops in
nemo_automodel.components.models.deepseek_v4.kernels. Upstream source: https://github.com/yueming-yuan/miles/tree/e561465d0b9bbf06188b7a5e2020dc7fd691f732/miles_plugins/models/deepseek_v4/ops Upstream license: Apache-2.0, copyright 2025 Zhipu AI. Seenemo_automodel/components/models/deepseek_v4/kernels/__init__.pyfor the per-file attribution.
Those packages are imported with safe_import so environments without
TileLang still import the model and use the existing torch path.
Module Contents
Classes
Functions
Data
API
Sparse-attention indices prepared once for every layer that consumes the same selection.
The sparse backend the layout is prepared for ("cudnn" or "tilelang").
"cudnn": contiguous int32 [batch * sequence, 1, padded_width] with global flat K/V
coordinates (per-batch offsets applied), an ascending valid prefix and a -1 suffix.
"tilelang": contiguous int32 [batch, sequence, slots] with -1 masked, the kernel layout.
Number of K/V positions per batch row the coordinates refer to.
"cudnn" only: contiguous int32 [batch * sequence] valid-prefix lengths.
"cudnn" with padded inputs only: int64 indices of the nonempty query rows, so the
backward skips its empty-row scan; None when every row is nonempty.
Bases: Function
TileKernels Sinkhorn wrapper that accepts non-contiguous backward gradients.
The upstream high-level wrapper launches the backward kernel with
grad_output as-is. DSV4 consumes HC combinations through transposed
matmul sites, so autograd can provide a transposed gradient layout. The
low-level TileKernels backward kernel requires contiguous row-major inputs.
Run the shared cuDNN sparse attention on batched DSV4 tensors.
Parameters:
BF16 queries [batch, sequence, heads, head_dim].
BF16 shared keys/values [batch, kv_sequence, head_dim].
FP32 per-head sink logits [heads].
Per-batch sparse indices [batch, sequence, slots] with -1 masked; None with plan.
Softmax scale.
Whether every query has at least one valid slot.
Optional prepared "cudnn" plan for this kv, replacing topk_idxs.
Returns: torch.Tensor
BF16 output [batch, sequence, heads, head_dim].
Turn per-batch [batch, sequence, slots] indices into int64 [batch * sequence, slots] global coordinates.
Build Miles-style top-k key indices for DSV4 local-window + compressed KV attention.
Parameters:
Optional pseudo-token types with shape [batch, sequence]. Text positions
contain -1; image spans contain IMAGE_START, IMAGE, and IMAGE_END token types.
When provided with max_image_tokens > 0, image queries additionally see the full image span.
Maximum number of tokens in an image span. 0 disables visual windowing.
Compute a dense FP32 oracle for top-k sparse attention.
Parameters:
Query tensor of shape [batch, sequence, heads, head_dim].
Shared key/value tensor of shape [batch, keys, head_dim].
Attention-sink logits of shape [heads].
Integer tensor [batch, sequence, topk]; -1 masks an entry.
Attention scaling factor.
Returns: torch.Tensor
Tensor [batch, sequence, heads, head_dim] in q’s dtype.
Run DSV4 C4 indexer scores through Miles TileLang kernels or torch fallback.
Run DSV4 C4 top-k indexer scores through Miles autograd kernels or torch fallback.
Normalize HyperConnection combination logits with torch or TileKernels.
Run sparse attention with an optional original-inference rounding mode.
Parameters:
BF16 queries [batch, sequence, heads, head_dim].
Shared keys/values [batch, kv_sequence, head_dim].
FP32 denominator biases [heads].
Sparse indices [batch, sequence, slots], with -1 masked; None only together
with plan, which then carries the prepared indices.
Query/key score multiplier.
Sparse execution backend.
Atomic or fixed-order deterministic backward (TileLang only).
Partial-KV workspace cap; auxiliary buffers are extra.
Scale logits before max reduction and use the original inference exponent arithmetic. Requires TileLang.
Whether every query has at least one valid slot ("cudnn").
Optional SparseIndexPlan from plan_dsv4_sparse_indices for this backend
and kv; it replaces the per-call index preparation of topk_idxs.
Returns: torch.Tensor
Attention output [batch, sequence, heads, head_dim], with q’s dtype.
Extract top-k score values, masking -1 entries with -inf.
Compute FP32 indexer scores for compressed key selection.
Parameters:
Query tensor of shape [batch, sequence, heads, head_dim].
Compressed keys of shape [batch, compressed, head_dim].
Head weights of shape [batch, sequence, heads].
Query/key scaling factor.
Returns: torch.Tensor
FP32 scores of shape [batch, sequence, compressed].
Return whether the optional TileLang kernel package for name is importable.
Prepare the per-call index work of dsv4_sparse_attention once for a shared selection.
Parameters:
Sparse indices [batch, sequence, slots] with -1 masked.
Number of K/V positions per batch row.
Sparse execution backend the plan is for.
Whether every query has at least one valid slot ("cudnn": when false the plan
also carries the nonempty rows, one host synchronisation per plan instead of one per layer backward).
Returns: SparseIndexPlan
The plan to pass as plan= to dsv4_sparse_attention together with the same kv.
Torch reference for TileKernels MHC Sinkhorn normalization.
Miles sparse MQA torch reference.
Parameters:
Query tensor with shape [B, S, H, D].
Single-head KV tensor with shape [B, K, D].
Per-head attention sink logits with shape [H].
Key indices with shape [B, S, K_top]; -1 masks an entry.
Attention scaling factor.