nemo_automodel.components.models.kimi_k3.cp
nemo_automodel.components.models.kimi_k3.cp
Context-parallel and packed-sequence support for Kimi Linear.
Kimi Linear interleaves KDA linear-attention layers with MLA full-attention layers, so context parallelism has to satisfy both at once:
- KDA carries a sequential recurrent state, so FLA’s context-parallel kernels
require every rank to own one contiguous slice of the global token stream
(rank
rowns[r * S / cp, (r + 1) * S / cp)) and take document boundaries throughcu_seqlens. PyTorch’s default load-balancedcontext_parallellayout (head/tail chunk swap) does not satisfy that, so Kimi Linear owns its batch sharding through_cp_make_batch_fn. - MLA attends globally. Under the contiguous layout each rank all-gathers the
compressed KV latent (
kv_lora_rank + qk_rope_head_dimvalues per token, roughly an order of magnitude smaller than the expanded per-head K/V) and runs FlexAttention with a causal, per-document block mask against the full-sequence keys.
Everything is driven by one [batch, sequence] document-id map (0 marks
padding, 1..n are 1-based document indices), which is also what makes packed
sequences work with and without CP.
Module Contents
Classes
Functions
Data
API
Per-step document layout shared by the KDA and MLA layers.
Whether the batch was sharded across a context-parallel mesh.
Whether any batch row contains more than one non-padding document.
Document ids of shape [batch, local_sequence] for this rank’s shard.
Return the global segment boundaries of one batch row.
Computed on first use (and cached for the step) because the device-to-host copy is only needed by the context-parallel path.
Parameters:
Batch row to describe.
Returns: torch.Tensor
The device and CPU copies of the row’s cumulative segment lengths, each
Bases: Function
Autograd-aware all-gather of equal-sized shards along the sequence axis.
Drop cached block masks when a new batch (new document map) arrives.
Build (and cache for the step) the FlexAttention document-causal block mask.
Resolve the global document-id map for a batch about to be CP-sharded.
All-gather a sequence-sharded tensor while keeping autograd connected.
Parameters:
Tensor of shape […, local_sequence, …] whose sequence axis is
selected by dim. Every rank must contribute the same shape.
Context-parallel process group.
Sequence axis.
Returns: torch.Tensor
Tensor with the sequence axis expanded to the full global sequence.
Build the additive causal mask that also blocks cross-document attention.
Parameters:
Tensor of shape [batch, query_sequence] with 1-based document ids.
Tensor of shape [batch, key_sequence] with 1-based document ids.
Global sequence offset of the first query token.
Floating-point dtype used for the additive mask values.
Returns: torch.Tensor
Additive mask tensor of shape [batch, 1, query_sequence, key_sequence].
Build FLA’s per-row context-parallel context for a KDA layer.
Parameters:
Context describing the global document layout.
Batch row the context is built for.
Context-parallel process group.
Short-convolution kernel size, used by FLA to exchange the conv boundary tokens between neighbouring ranks.
Returns:
The FLA FLACPContext for this row.
Build document ids from a binary or indexed attention mask.
Parameters:
Tensor of shape [batch, sequence]. A binary mask marks
valid tokens with 1; an Automodel packing mask marks document i
(1-based) with the value i and padding with 0.
Returns: torch.Tensor
Tensor of shape [batch, sequence] with 1-based document ids and 0 for
Build single-row document ids from cumulative sequence lengths.
Parameters:
Tensor of shape [segments + 1] with cumulative token counts. THD batches pad unused entries with a negative sentinel, which is dropped here.
Sequence length of the batch’s token tensors.
Returns: torch.Tensor
Tensor of shape [1, sequence] with 1-based document ids and 0 for the
Build document ids from the packed-sequence collater’s seq_lens.
Parameters:
Tensor of shape [batch, packs] with per-pack token counts, using
padding_value for unused pack slots.
Sequence length of the batch’s token tensors.
Sentinel marking unused pack slots.
Returns: torch.Tensor
Tensor of shape [batch, sequence] with 1-based document ids and 0 for the
Run causal, per-document attention of local queries against global keys.
Parameters:
Tensor of shape [batch, heads, query_sequence, qk_head_dim].
Tensor of shape [batch, heads, key_sequence, qk_head_dim].
Tensor of shape [batch, heads, key_sequence, v_head_dim].
Tensor of shape [batch, query_sequence] with 1-based document ids.
Tensor of shape [batch, key_sequence] with 1-based document ids.
Global sequence offset of the first query token.
Softmax scale applied to the query-key product.
Returns: torch.Tensor
Tensor of shape [batch, heads, query_sequence, v_head_dim].
Return segment boundaries for one row of document ids.
Consecutive runs of the same id — including runs of padding — become their own segment so that the boundaries always tile the full row, which is what FLA’s context-parallel partitioning expects.
Parameters:
Tensor of shape [sequence] with 1-based document ids.
Returns: torch.Tensor
Tensor of shape [segments + 1] with cumulative segment lengths.
Shard a batch contiguously across the context-parallel mesh for Kimi K3.
Exposed through the :class:ContextParallelSharder returned by
:meth:KimiK3ForCausalLM.prepare_model_inputs_for_cp. Every rank starts
from the same full batch, keeps the [seq_start, seq_end) slice of each
sequence-aligned tensor, and gets the (unsharded) global document-id map
needed by the KDA and MLA layers.
Parameters:
One-dimensional context-parallel mesh, or None.
Tensor-parallel mesh; unused, accepted for interface parity.
Batch mapping containing input_ids of shape [batch, sequence]
plus labels and optional sequence-aligned tensors.
Optional tensor of shape [batch, sequence] sharded with the labels.
Token id used when padding input_ids.
Returns:
(context_factory, batch, layout); the context factory is a null