Skip to navigation

nemo_automodel.components.models.glm_moe_dsa.cp

View as MarkdownOpen in Claude

Context-parallel helpers for GLM MoE DSA TileLang attention.

Module Contents

Classes

NameDescription
_GatherToGlobalPermute a rank-order gather into global token order; the backward permutes the gradient back.
_ReplayedAllGatherReturn a recorded all-gather result while keeping the gradient path of the gather.

Functions

NameDescription
_packed_cp_layout-
_slice_thd_chunk_for_cp-
_waitComplete an asynchronous functional collective result.
gather_orderRow maps between the rank-order all-gather of layout shards and global token order.
glm_dsa_cp_all_gatherAll-gather an activation across CP ranks along dim while preserving autograd.
glm_dsa_cp_enabledReturn whether a real GLM DSA CP process group is active.
layout_indices_for_rankGlobal query positions rank rank of cp_size owns under layout, in its local order.
local_query_indicesReturn this rank’s global query positions for layout (see QueryLayout).
make_glm_dsa_packed_cp_batch_and_ctxConvert packed GLM DSA batches to THD and keep one query shard per CP rank.
shard_glm_dsa_packed_cp_batchContextParallelSharder.shard_batch wrapper for GLM DSA packed CP.
validate_query_rowsCheck that the batch’s query rows are the rows layout assigns to this rank.

Data

GatherOrder

QUERY_LAYOUTS

QueryLayout

glm_dsa_gather_replay

API

class nemo_automodel.components.models.glm_moe_dsa.cp._GatherToGlobal()

Bases: Function

Permute a rank-order gather into global token order; the backward permutes the gradient back.

nemo_automodel.components.models.glm_moe_dsa.cp._GatherToGlobal.backward(
ctx: typing.Any,
grad_global: torch.Tensor
) -> tuple[torch.Tensor, None, None, None]
staticmethod

Map the global-order gradient back onto the rank-order gather.

nemo_automodel.components.models.glm_moe_dsa.cp._GatherToGlobal.forward(
ctx: typing.Any,
gathered: torch.Tensor,
from_global: torch.Tensor,
to_global: torch.Tensor,
dim: int
)
staticmethod

Reorder gathered so that index i along dim holds global token i.

Parameters:

ctx
Any

Autograd context.

gathered
torch.Tensor

Rank-order all-gather result.

from_global
torch.Tensor

Global token held by each gathered row (see gather_order).

to_global
torch.Tensor

Gathered row holding each global token.

dim
int

Gather dimension.

Returns:

The gathered tensor in global token order.

class nemo_automodel.components.models.glm_moe_dsa.cp._ReplayedAllGather()

Bases: Function

Return a recorded all-gather result while keeping the gradient path of the gather.

nemo_automodel.components.models.glm_moe_dsa.cp._ReplayedAllGather.backward(
ctx: typing.Any,
grad_gathered: torch.Tensor
) -> tuple[torch.Tensor, None, None, None, None]
staticmethod

Reduce-scatter the gathered gradient back to each rank’s shard, as the gather’s backward does.

nemo_automodel.components.models.glm_moe_dsa.cp._ReplayedAllGather.forward(
ctx: typing.Any,
local: torch.Tensor,
gathered: torch.Tensor,
dim: int,
cp_group,
from_global: torch.Tensor | None
) -> torch.Tensor
staticmethod

Hand back gathered (the forward’s all-gather of local) without communicating.

Parameters:

ctx
Any

Autograd context.

local
torch.Tensor

This rank’s shard, only used for its gradient shape and dtype.

gathered
torch.Tensor

The recorded all-gather of local across the CP group along dim, in global token order when from_global is given and in rank order otherwise.

dim
int

Gather dimension.

cp_group

CP process group.

from_global
torch.Tensor | None

Global token held by each rank-order gathered row when the recorded tensor was reordered into global order (see gather_order); None for rank order.

Returns: torch.Tensor

gathered as a fresh view.

nemo_automodel.components.models.glm_moe_dsa.cp._packed_cp_layout(
batch,
num_chunks: int
nemo_automodel.components.models.glm_moe_dsa.cp._slice_thd_chunk_for_cp(
chunk: dict[str, torch.Tensor],
cp_mesh,
cp_group,
cp_size: int,
cp_rank: int,
padding_token_id: int,
) -> dict[str, torch.Tensor]
nemo_automodel.components.models.glm_moe_dsa.cp._wait(
tensor: torch.Tensor
) -> torch.Tensor

Complete an asynchronous functional collective result.

nemo_automodel.components.models.glm_moe_dsa.cp.gather_order(
cp_size: int,
total_tokens: int,
device: torch.device

Row maps between the rank-order all-gather of layout shards and global token order.

all_gather_tensor_autograd concatenates the ranks’ shards in rank order, so gathered row r * T/cp + j holds the j-th local token of rank r. Every consumer of the gathered K/V (the cuDNN packed metadata’s key sources and causal windows, the top-k coordinates FlashMLA and cuDNN read kv_latent with, the TileLang causal windows) addresses rows by global token position, which coincides with rank order only for the contiguous layout.

Parameters:

layout
QueryLayout

Query layout the batch was sliced with.

cp_size
int

Context-parallel world size.

total_tokens
int

Global padded token count (local tokens times cp_size).

device
torch.device

Device of the returned index tensors.

Returns: GatherOrder | None

None when rank order already is global order (contiguous layout, or cp_size <= 1);

nemo_automodel.components.models.glm_moe_dsa.cp.glm_dsa_cp_all_gather(
tensor: torch.Tensor,
dim: int,
cp_group,
replay: nemo_automodel.shared.recompute_replay.RecomputeReplay[torch.Tensor] | None = None,
) -> torch.Tensor

All-gather an activation across CP ranks along dim while preserving autograd.

One functional collective produces the concatenated result directly (no per-rank list and concat copy), and its backward reduce-scatters the gradient to the owning ranks. With replay bound in record mode the gathered tensor is recorded; in replay mode (the activation-checkpoint recompute) the recorded tensor is returned without communication, with the same gradient path.

Parameters:

tensor
torch.Tensor

This rank’s shard; [local_tokens, ...] for dim=0.

dim
int

Concatenation dimension.

cp_group

CP process group; a size-one or missing group returns tensor unchanged.

replay
RecomputeReplay[torch.Tensor] | NoneDefaults to None

Optional record/replay channel consulted inside a checkpointed block.

order
GatherOrder | NoneDefaults to None

Optional gather_order maps; when given, the result is permuted from rank order into global token order (and the backward permutes the gradient back). Required for every layout whose rank order is not global order, such as head/tail.

Returns: torch.Tensor

Tensor whose dim holds every rank’s shard in rank order, or in global token order when

nemo_automodel.components.models.glm_moe_dsa.cp.glm_dsa_cp_enabled(
cp_group
) -> bool

Return whether a real GLM DSA CP process group is active.

nemo_automodel.components.models.glm_moe_dsa.cp.layout_indices_for_rank(
rank: int,
cp_size: int,
total_tokens: int,
device: torch.device
) -> torch.Tensor

Global query positions rank rank of cp_size owns under layout, in its local order.

Mesh-free form of contiguous_local_indices / round_robin_local_indices, which the batch slicer uses for the calling rank; this one serves every rank so gather_order can describe the whole gathered tensor.

Parameters:

layout
QueryLayout

Query layout, see QueryLayout.

rank
int

Context-parallel rank in [0, cp_size).

cp_size
int

Context-parallel world size.

total_tokens
int

Global padded token count; a multiple of cp_size (contiguous) or 2 * cp_size (head/tail).

device
torch.device

Device of the returned index tensor.

Returns: torch.Tensor

Int64 tensor of shape [total_tokens / cp_size] with the rank’s global token positions in

nemo_automodel.components.models.glm_moe_dsa.cp.local_query_indices(
cp_mesh,
total_tokens: int,
device: torch.device
) -> torch.Tensor

Return this rank’s global query positions for layout (see QueryLayout).

nemo_automodel.components.models.glm_moe_dsa.cp.make_glm_dsa_packed_cp_batch_and_ctx(
cp_mesh,
tp_mesh,
batch,
loss_mask = None,
padding_token_id: int = 0,
num_chunks: int = 1,
seq_lens_padding_value: int = -1000,
)

Convert packed GLM DSA batches to THD and keep one query shard per CP rank.

GLM DSA sparse attention gathers K/V activations inside the model. The batch side only slices local query tokens (query_layout decides which, see QueryLayout) and carries the full packed-sequence cu_seqlens plus per-query global token indices for the kernels’ causal top-k windows.

nemo_automodel.components.models.glm_moe_dsa.cp.shard_glm_dsa_packed_cp_batch(
cp_mesh,
tp_mesh,
batch,
loss_mask = None,
padding_token_id: int = 0,
num_chunks: int = 1,
seq_lens_padding_value: int = -1000,
generated_rows: bool = False
)

ContextParallelSharder.shard_batch wrapper for GLM DSA packed CP.

generated_rows is set by the model’s own sharder: the query rows were just generated for query_layout, so the batch carries them with that layout (_glm_dsa_shard_rows and _glm_dsa_shard_layout) and the model compares layouts instead of reading the rows back from the device. Callers that supply glm_dsa_cp_query_indices themselves leave it False and get the value check in validate_query_rows.

nemo_automodel.components.models.glm_moe_dsa.cp.validate_query_rows(
cp_rank: int,
cp_size: int,
local_tokens: int,
query_indices: torch.Tensor
) -> None

Check that the batch’s query rows are the rows layout assigns to this rank.

The K/V gather and every kernel after it assume the configured layout, so rows sliced with another layout would make the kernels read wrong keys. This holds for the contiguous layout too: its gather keeps rank order, which is global order only for contiguous shards.

Parameters:

layout
QueryLayout

The model’s configured query layout (BackendConfig.cp_query_layout).

cp_rank
int

This rank’s index in the context-parallel group.

cp_size
int

Context-parallel world size.

local_tokens
int

Number of local query rows.

query_indices
torch.Tensor

The batch’s glm_dsa_cp_query_indices (global positions of the local rows).

Raises:

  • ValueError: If the batch was sliced with a different layout than the configured one.
nemo_automodel.components.models.glm_moe_dsa.cp.GatherOrder = tuple[torch.Tensor, torch.Tensor]
nemo_automodel.components.models.glm_moe_dsa.cp.QUERY_LAYOUTS: tuple[QueryLayout, ...] = ('contiguous', 'head_tail')
nemo_automodel.components.models.glm_moe_dsa.cp.QueryLayout = Literal['contiguous', 'head_tail']
nemo_automodel.components.models.glm_moe_dsa.cp.glm_dsa_gather_replay: RecomputeReplay[Tensor] = RecomputeReplay('GLM DSA CP gathered latent')