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.
Number of context-parallel shards the global sequence was split into.
Global document ids of shape [batch, sequence] covering the full
(unsharded) sequence, where 0 marks padding. In indexed packed masks,
each positive document ID must occupy one contiguous run per row once
masked (0) gaps are ignored: [1, 1, 0, 1, 1, 2, 2] is one document
with a masked hole, [1, 2, 1] is rejected.
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 document-causal mask retained through this microbatch’s backward.
Global sequence offset of the local shard; 0 without CP.
Cache cuDNN metadata for one row’s local queries and global keys.
Parameters:
Batch row in the document map of shape [batch, global_sequence].
Returns: CudnnDsaPackedMetadata
Segmented cuDNN metadata with row-local global key coordinates.
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.
Build the FlexAttention mask owned by one microbatch’s packed context.
Parameters:
Local query document IDs of shape [batch, local_sequence].
Global key document IDs of shape [batch, global_sequence].
Offset of the contiguous local query shard.
Returns: BlockMask
BlockMask for local queries against global keys, causal within documents.
Resolve the global document-id map for a batch about to be CP-sharded.
Parameters:
Model inputs. _packed_seq_ids or a rank-two attention_mask
carries document IDs of shape [batch, sequence]; seq_lens and
seq_lens_padded have shape [batch, documents]; padding_mask
and input_ids have shape [batch, sequence].
Global sequence length before context-parallel sharding.
Device of the global token tensors.
Returns: torch.Tensor
Int32 document IDs of shape [batch, sequence], with zero marking padding.
Return a stable per-row order that moves masked tokens behind valid tokens.
Without CP, KDA compacts masked tokens away, so a masked span inside a document, such as an injected fake image, does not interrupt that document’s convolution or recurrent state. FLA’s CP kernels instead start a new segment at every document-id change. Moving masked tokens to the row’s trailing padding gives every CP rank the non-CP valid-token sequence; K3 attention applies no rotary positions, so only the relative order of valid tokens matters.
Parameters:
Document IDs of shape [batch, sequence], with zero marking masked tokens.
Returns: torch.Tensor | None
Source indices of shape [batch, sequence], or None when no masked
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: FLACPContext
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
Mark the keys each query may attend to: causal and within its own document.
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.
Returns: torch.Tensor
Boolean tensor of shape [batch, query_sequence, key_sequence], true where attention is allowed.
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.
Document-causal mask prepared outside checkpointed decoder layers.
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 ContextParallelSharder returned by
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
Keep complete media token streams until embedding inside the VLM forward.
Labels, positions, masks, and global document metadata use the text model’s contiguous CP layout. The full primary stream is batch-chunkable for PP.
Parameters:
Context-parallel mesh, or None for a single context rank.
Tensor-parallel mesh passed to the native text sharder.
Mutable VLM batch. input_ids, labels, position_ids and document masks have shape [batch, global_sequence]; pixel_values has shape [patches, channels, patch_height, patch_width] and image grids have shape [images, 3]. Media tensors remain replicated over CP.
Optional tensor of shape [batch, global_sequence].
Token ID used for sequence alignment.
Returns: Callable[[], contextlib.AbstractContextManager[None]]
Context factory, mutated batch, and original/padded sequence lengths.
Build a FlexAttention mask from a dense DSA keep-mask.
Parameters:
Boolean tensor of shape [batch, query_sequence, key_sequence], true where a query attends. It already folds in the causal and document constraints.
Returns: BlockMask
BlockMask for local queries against global keys that reads keep directly.