Skip to navigation

nemo_automodel.components.models.glm5_next.cp

View as MarkdownOpen in Claude

Contiguous packed context parallelism for GLM-5.3-Flash.

Kimi Delta Attention carries recurrent and short-convolution state from left to right, so the generic load-balanced CP permutation is not valid. This module keeps one contiguous token interval per CP rank and one global document-id map that both KDA and KPool-DSA consume.

Module Contents

Classes

NameDescription
Glm5NextPackedContextGlobal packed-document layout for one model step.
Glm5NextPackedMetadataPacked-document layout in the form the PP kwargs splitter can chunk.
_AllGatherBackwardAnchorReturn zero while retaining a backward edge to a gathered tensor.
_AllGatherSequenceAutograd-aware all-gather of equal contiguous sequence shards.

Functions

NameDescription
_global_doc_ids_from_batchResolve the global document map before removing packing metadata.
_normalize_batch_axisRestore the placeholder batch axis used by THD VLM collaters.
_pad_sequence_dim-
all_gather_backward_anchorCreate a zero-valued dependency that keeps gather backward collective-safe.
all_gather_sequenceGather a sequence-sharded tensor while preserving K/V gradient flow.
build_fla_cp_contextBuild FLA’s KDA context for one batch row.
doc_ids_from_cu_seqlensConvert cumulative document boundaries to ids [1, sequence].
doc_ids_from_seq_lensConvert per-document lengths [batch, documents] to ids [batch, sequence].
segment_cu_seqlensReturn boundaries for consecutive document-id runs covering the full row.
shard_batch_for_glm5_next_cpContiguously shard packed GLM-5.3 token streams.

Data

_PAD_DOC_ID

API

class nemo_automodel.components.models.glm5_next.cp.Glm5NextPackedContext(
doc_ids: torch.Tensor,
seq_start: int = 0,
cp_size: int = 1,
original_seq_len: int | None = None,
_cu_seqlens: dict[int, tuple[torch.Tensor, torch.Tensor]] = dict(),
_document_ranges: dict[int, tuple[tuple[int, int], ...]] = dict()
)
Dataclass

Global packed-document layout for one model step.

_cu_seqlens
dict[int, tuple[Tensor, Tensor]]
_document_ranges
dict[int, tuple[tuple[int, int], ...]]
cp_enabled
bool

Return whether the sequence is split across more than one rank.

cp_size
int = 1

Number of context-parallel ranks.

doc_ids
Tensor

Integer document ids [batch, global_sequence]. Zero marks padding and positive values identify independent packed documents.

local_doc_ids
Tensor

Return document ids [batch, local_sequence] for this rank.

local_seq_len
int

Return the padded local sequence length.

original_seq_len
int | None = None

Sequence length before CP divisibility padding.

seq_start
int = 0

Global offset of this rank’s contiguous local token interval.

nemo_automodel.components.models.glm5_next.cp.Glm5NextPackedContext.row_cu_seqlens(
row: int
) -> tuple[torch.Tensor, torch.Tensor]

Return device/CPU segment boundaries for one packed batch row.

nemo_automodel.components.models.glm5_next.cp.Glm5NextPackedContext.row_document_ranges(
row: int
) -> tuple[tuple[int, int], ...]

Return cached non-padding document ranges in global row coordinates.

Document ids are immutable for the lifetime of this per-step context. Materialize the cache before decoder FSDP hooks rebuild the dataclass.

class nemo_automodel.components.models.glm5_next.cp.Glm5NextPackedMetadata()

Bases: NamedTuple

Packed-document layout in the form the PP kwargs splitter can chunk.

The splitter splits doc_ids along the batch axis and replicates the integers, and returns the same NamedTuple type per microbatch; it treats a dataclass as one replicated value.

cp_size
int

Number of context-parallel ranks.

doc_ids
Tensor

Integer document ids [batch, global_sequence].

original_seq_len
int

Sequence length before CP divisibility padding.

seq_start
int

Global offset of this rank’s contiguous local token interval.

class nemo_automodel.components.models.glm5_next.cp._AllGatherBackwardAnchor()

Bases: Function

Return zero while retaining a backward edge to a gathered tensor.

nemo_automodel.components.models.glm5_next.cp._AllGatherBackwardAnchor.backward(
ctx,
grad_output: torch.Tensor
) -> torch.Tensor
staticmethod

Send a zero gradient to the gathered tensor.

Parameters:

ctx

Autograd context saved by forward.

grad_output
torch.Tensor

Tensor of shape [batch, 1, 1].

Returns: torch.Tensor

Zero tensor with the forward input’s shape [batch,

nemo_automodel.components.models.glm5_next.cp._AllGatherBackwardAnchor.forward(
ctx,
gathered: torch.Tensor
) -> torch.Tensor
staticmethod

Return a broadcastable zero tied to gathered.

Parameters:

ctx

Autograd context; stores the input shape for backward.

gathered
torch.Tensor

Tensor of shape [batch, global_sequence, hidden], the all-gathered sequence.

Returns: torch.Tensor

Zero tensor of shape [batch, 1, 1] in gathered’s dtype and

class nemo_automodel.components.models.glm5_next.cp._AllGatherSequence()

Bases: Function

Autograd-aware all-gather of equal contiguous sequence shards.

nemo_automodel.components.models.glm5_next.cp._AllGatherSequence.backward(
ctx,
grad_output: torch.Tensor
)
staticmethod

Reduce a private copy of the full-sequence gradient.

Parameters:

ctx

Autograd context saved by forward.

grad_output
torch.Tensor

Tensor with the forward output’s shape, global sequence on ctx.dim. Its dtype matches the forward input, and its storage may still be owned by the caller or another autograd branch.

Returns:

Local sequence-gradient tensor, followed by two None entries for

nemo_automodel.components.models.glm5_next.cp._AllGatherSequence.forward(
ctx,
local_tensor: torch.Tensor,
group: typing.Any,
dim: int
) -> torch.Tensor
staticmethod

Concatenate every rank’s sequence shard in rank order.

Parameters:

ctx

Autograd context; stores the group, dimension, rank and local shard length for backward.

local_tensor
torch.Tensor

Tensor of arbitrary rank whose dim axis is this rank’s local_sequence shard. Every rank must pass the same shape and dtype.

group
Any

Context-parallel process group of size cp_size.

dim
int

Sequence axis; negative values count from the end.

Returns: torch.Tensor

Contiguous tensor with local_tensor’s shape except that axis

nemo_automodel.components.models.glm5_next.cp._global_doc_ids_from_batch(
batch: dict[str, typing.Any],
seq_len: int
) -> torch.Tensor

Resolve the global document map before removing packing metadata.

nemo_automodel.components.models.glm5_next.cp._normalize_batch_axis(
batch: dict[str, typing.Any]
) -> None

Restore the placeholder batch axis used by THD VLM collaters.

nemo_automodel.components.models.glm5_next.cp._pad_sequence_dim(
tensor: torch.Tensor,
pad_len: int,
value: float | int | bool
) -> torch.Tensor
nemo_automodel.components.models.glm5_next.cp.all_gather_backward_anchor(
gathered: torch.Tensor
) -> torch.Tensor

Create a zero-valued dependency that keeps gather backward collective-safe.

nemo_automodel.components.models.glm5_next.cp.all_gather_sequence(
tensor: torch.Tensor,
cp_group: typing.Any,
dim: int = 1
) -> torch.Tensor

Gather a sequence-sharded tensor while preserving K/V gradient flow.

nemo_automodel.components.models.glm5_next.cp.build_fla_cp_context(
row: int,
cp_group: typing.Any,
conv_kernel_size: int
)

Build FLA’s KDA context for one batch row.

Parameters:

packed_context
Glm5NextPackedContext

Global document layout whose doc_ids tensor has shape [batch, padded_global_sequence]. Its cached device and CPU boundaries, each an integer tensor of shape [segments + 1] where segments are consecutive equal-id runs including padding, are read; FLA receives a fresh clone of the device boundaries.

row
int

Batch row being executed.

cp_group
Any

Context-parallel process group.

conv_kernel_size
int

Short-convolution width used for the left halo.

Returns:

FLA FLACPContext carrying segment and process-group metadata.

nemo_automodel.components.models.glm5_next.cp.doc_ids_from_cu_seqlens(
cu_seqlens: torch.Tensor,
seq_len: int
) -> torch.Tensor

Convert cumulative document boundaries to ids [1, sequence].

nemo_automodel.components.models.glm5_next.cp.doc_ids_from_seq_lens(
seq_lens: torch.Tensor,
seq_len: int,
padding_value: int = -1000
) -> torch.Tensor

Convert per-document lengths [batch, documents] to ids [batch, sequence].

nemo_automodel.components.models.glm5_next.cp.segment_cu_seqlens(
doc_ids_row: torch.Tensor
) -> torch.Tensor

Return boundaries for consecutive document-id runs covering the full row.

nemo_automodel.components.models.glm5_next.cp.shard_batch_for_glm5_next_cp(
cp_mesh: torch.distributed.device_mesh.DeviceMesh | None,
tp_mesh: torch.distributed.device_mesh.DeviceMesh | None,
batch: dict[str, typing.Any],
loss_mask: torch.Tensor | None = None,
padding_token_id: int = 0,
shard_primary: bool = False,
num_chunks: int = 1
) -> tuple[collections.abc.Callable[[], contextlib.AbstractContextManager[None]], dict[str, typing.Any], nemo_automodel.components.distributed.context_parallel.sharder.ShardLayout]

Contiguously shard packed GLM-5.3 token streams.

The top-level VLM uses shard_primary=False: image features must be spliced into the full embedding sequence inside forward before that differentiable primary stream is sliced. Labels and other no-grad token streams are still sharded here.

Parameters:

cp_mesh
DeviceMesh | None

One-dimensional CP mesh or None.

tp_mesh
DeviceMesh | None

Unused tensor-parallel mesh, accepted by the sharder protocol.

batch
dict[str, Any]

Batch mutated in place. Token tensors such as input_ids, labels, position_ids and padding_mask have shape [batch, sequence] (a 1-D THD row gains a batch axis). Packing metadata (_packed_seq_ids or attention_mask of shape [batch, sequence], seq_lens/seq_lens_padded of shape [batch, documents], or cu_seqlens of shape [documents + 1]) is consumed and removed.

loss_mask
torch.Tensor | NoneDefaults to None

Optional tensor of shape [batch, sequence].

padding_token_id
intDefaults to 0

Fill value for padded token ids.

shard_primary
boolDefaults to False

Whether to shard input_ids in this function.

num_chunks
intDefaults to 1

PP microbatches. With multiple chunks, expose the document map as a tensor in a tuple so Torch splits its batch axis too.

Returns: Callable[[], AbstractContextManager[None]]

Context factory, mutated local batch, and the global shard layout.

nemo_automodel.components.models.glm5_next.cp._PAD_DOC_ID = 0