core.datasets.data_schedule_utils#

Module Contents#

Functions#

get_packed_sequence_alignment

Return CP-local alignment and whether post-pack padding is enabled.

get_packed_sequence_length

Return the physical length used by eager per-sequence zigzag padding.

_pad_packed_graph_metadata

Fix metadata shapes without treating physical padding as real tokens.

pad_packed_batch_before_cp_slice

Pad global THD data and metadata before constructing any CP layout.

_unpack_batch

Unpacks the packed samples into a list of sub-samples. Since each sub-sample may be routed to different DPxCP ranks, we unpack the sample here to avoid unnecessarily transferring the entire packed sample.

_get_global_seqlens_and_ids

Gathers the sequence lengths of all subsamples from all DP ranks and calculates global IDs.

_pack_sequences

Pack multiple samples into a single packed sample.

broadcast_tensor

Broadcast a tensor from src_rank to all ranks in the group.

broadcast_scalars

Broadcast scalar values from rank 0 to all ranks in the group.

create_data_iterator

Build packed-data iterators for the local pipeline stage.

reroute_samples_to_dcp_ranks

Reroutes the sub-samples to the correct rank after scheduling.

build_packed_microbatches

Build this rank’s packed samples and attach its runtime CP size.

get_batch_and_global_seqlens

Get the batch and global sequence lengths. Each DP rank loads the same number of sequences, so we need to gather the sequence lengths from all ranks then we can schedule the sequences into groups.

get_global_real_seqlen_stats

Sum the real (unpadded) sub-sample lengths of the global batch and their squares.

next_dynamic_cp_group_packing_aware

Form one DCP microbatch with packing-aware CP group selection.

align_sample_id_groups

Split microbatches for VPP without dropping samples or inventing CP groups.

Data#

API#

core.datasets.data_schedule_utils._DYNAMIC_CP_WORKLOAD_CAP_DELTA#

0.05

core.datasets.data_schedule_utils._REROUTE_KEY_ORDER#

(‘tokens’, ‘labels’, ‘loss_mask’, ‘position_ids’, ‘original_seq_len’, ‘padded_seq_len’)

core.datasets.data_schedule_utils._REROUTE_KEY_SET#

‘frozenset(…)’

core.datasets.data_schedule_utils._REROUTE_SCALAR_KEYS#

‘frozenset(…)’

core.datasets.data_schedule_utils._SequenceLength#

‘TypeVar(…)’

core.datasets.data_schedule_utils.get_packed_sequence_alignment(
config,
tp_size: int,
) → tuple[int, bool]#

Return CP-local alignment and whether post-pack padding is enabled.

The user-facing alignment is in pre-SP units. MXFP8’s quantization block constraint applies after SP and must therefore include the TP size.

core.datasets.data_schedule_utils.get_packed_sequence_length(
seq_len: core.datasets.data_schedule_utils._SequenceLength,
cp_size: int,
pad_sequences: bool,
) → core.datasets.data_schedule_utils._SequenceLength#

Return the physical length used by eager per-sequence zigzag padding.

core.datasets.data_schedule_utils._pad_packed_graph_metadata(
batch: Dict,
max_num_seqs: Optional[int],
) → None#

Fix metadata shapes without treating physical padding as real tokens.

core.datasets.data_schedule_utils.pad_packed_batch_before_cp_slice(
batch: Dict,
config,
cp_size: int,
tp_size: int,
) → None#

Pad global THD data and metadata before constructing any CP layout.

Preserve compact logical boundaries and existing physical gaps. Align each physical sequence for zigzag CP, then append a masked dummy sequence to reach the requested CP-local alignment. For fixed graph metadata the dummy has zero logical length; the ordinary main padding contract is unchanged.

core.datasets.data_schedule_utils._unpack_batch(
batch: List[Dict[str, torch.Tensor]],
) → List[Dict[str, torch.Tensor]]#

Unpacks the packed samples into a list of sub-samples. Since each sub-sample may be routed to different DPxCP ranks, we unpack the sample here to avoid unnecessarily transferring the entire packed sample.

Two mutually exclusive input shapes are accepted, and every sample in batch must use the same one:

  • Pre-packed (e.g. :class:SFTDataset): each sample carries a cu_seqlens tensor and the tokens of multiple sub-samples concatenated together. We slice them apart and synthesize original_seq_len / padded_seq_len from the cu_seqlens deltas.

  • Already unpacked (e.g. :class:VarlenDataset): each sample is a single sub-sample that already carries padded_seq_len (and usually original_seq_len). We just normalize the leading batch dimension introduced by the default collate_fn and return as-is.

The shape is decided once for the whole batch and asserted per sample, so a dataset that emits both keys cannot silently bypass the cu_seqlens slicing below.

core.datasets.data_schedule_utils._get_global_seqlens_and_ids(subsample_seqlens: torch.Tensor, dp_group)#

Gathers the sequence lengths of all subsamples from all DP ranks and calculates global IDs.

core.datasets.data_schedule_utils._pack_sequences(
samples: List,
padded_lengths: torch.Tensor,
original_lengths: torch.Tensor,
local_cp_size: Optional[torch.Tensor],
dev: torch.device,
) → Dict[str, torch.Tensor]#

Pack multiple samples into a single packed sample.

core.datasets.data_schedule_utils.broadcast_tensor(item, src_rank, group) → None#

Broadcast a tensor from src_rank to all ranks in the group.

core.datasets.data_schedule_utils.broadcast_scalars(
values: List,
group,
dev,
dtype=torch.float32,
) → List#

Broadcast scalar values from rank 0 to all ranks in the group.

Parameters:
  • values – List of scalar values to broadcast (only used on rank 0).

  • group – The process group to broadcast within.

  • dev – The device to use for the tensor.

  • dtype – The data type for the tensor.

Returns:

List of broadcasted values.

core.datasets.data_schedule_utils.create_data_iterator(
new_samples,
tp_group,
config,
vpp_needs_data=None,
is_dynamic_cp: bool = False,
)#

Build packed-data iterators for the local pipeline stage.

Every virtual stage gets an independent RerunDataIterator. Stages at the model boundary, and stages containing MTP, receive the data fields; all other virtual stages receive only packed-sequence metadata.

core.datasets.data_schedule_utils.reroute_samples_to_dcp_ranks(
batch,
global_ids_this_rank,
global_id_seqlens,
sample_id_groups,
offsets,
dp_group,
dp_cp_group,
sample_keys=None,
)#

Reroutes the sub-samples to the correct rank after scheduling.

Each CP lane gathers the samples from its DP group, then keeps only the samples assigned to its DPxCP rank. Gathering within dp_group avoids collecting the identical input held by every CP sibling and avoids the fully connected P2P transport created by NCCL all-to-all.

The gather is issued one data key at a time to bound temporary memory to one global field. Selected slices are cloned before the next key so the full gather buffer can be released.

This is intentionally a text-only contract. Multimodal fields are rejected until their per-token, per-sample, or per-media routing layout is defined.

core.datasets.data_schedule_utils.build_packed_microbatches(
samples_this_rank_with_id: Dict[int, Dict[str, torch.Tensor]],
sample_id_groups: List[List[List[int]]],
dcp_rank: int,
dev: torch.device,
is_dynamic_cp: bool = False,
) → List[Dict[str, torch.Tensor]]#

Build this rank’s packed samples and attach its runtime CP size.

core.datasets.data_schedule_utils.get_batch_and_global_seqlens(
data_iterator,
num_microbatches,
dp_group,
)#

Get the batch and global sequence lengths. Each DP rank loads the same number of sequences, so we need to gather the sequence lengths from all ranks then we can schedule the sequences into groups.

Parameters:
  • data_iterator – The data iterator.

  • num_microbatches – The number of microbatches.

  • dp_group – The data parallel group.

Returns:

The sub-samples pulled from this rank’s data_iterator over num_microbatches steps, flattened and unpacked (see :func:_unpack_batch). Every dict carries tokens / labels / loss_mask / position_ids plus the original_seq_len and padded_seq_len scalars used for scheduling. global_id_seqlens (List[Tuple[int, int]]): (global_id, padded_seq_len) for every sub-sample in the DP group, ordered by DP rank and then by local index. Identical on all ranks; this is the scheduler’s input. global_ids_this_rank (torch.Tensor): int32 CUDA tensor holding the global IDs of the sub-samples loaded by this rank, i.e. batch[i] has global ID global_ids_this_rank[i]. offsets (torch.Tensor): int32 CPU tensor of shape [dp_size + 1] with the exclusive prefix sum of the per-rank sub-sample counts, so DP rank r owns global IDs offsets[r]:offsets[r + 1]. Used by :func:reroute_samples_to_dcp_ranks to map a global ID back to its source rank. seqlens_gathered (List[int]): Padded sequence length of every sub-sample in the DP group, indexed by global ID (seqlens_gathered[gid] equals global_id_seqlens[gid][1]). These lengths size the schedule; FLOPs accounting counts real tokens with :func:get_global_real_seqlen_stats.

Return type:

batch (List[Dict[str, torch.Tensor]])

core.datasets.data_schedule_utils.get_global_real_seqlen_stats(
batch,
dp_group,
dev,
) → Tuple[float, float]#

Sum the real (unpadded) sub-sample lengths of the global batch and their squares.

Parameters:
  • batch – This DP rank’s sub-samples as returned by :func:get_batch_and_global_seqlens.

  • dp_group – The DP group whose padded lengths were gathered for scheduling.

  • dev – Device for the reduction.

Returns:

(sum_i L_i, sum_i L_i**2) over the real lengths L_i of every sub-sample in dp_group, as expected by num_floating_point_operations.

core.datasets.data_schedule_utils.next_dynamic_cp_group_packing_aware(
sample_seqlens: List[Tuple[int, int]],
total_gpus: int,
max_seq_len_per_rank: int,
min_cp_size: int = 1,
cp_group_sizes: Optional[Sequence[int]] = None,
pad_sequences: bool = False,
) → Tuple[List[List[int]], List[Tuple[int, int]], List[float], List[List[int]]]#

Form one DCP microbatch with packing-aware CP group selection.

This differs from the legacy DCP scheduler in two ways:

  1. Short sequences may use a larger CP group than their minimum required CP size when that lowers the critical-path rank workload.

  2. Candidate placements are bounded by tall * max_seq_len_per_rank, the per-rank workload upper bound for packing sequences no longer than the local tallest sequence in the microbatch.

The scheduler keeps the legacy invariant that each returned microbatch has no empty DPxCP rank after the fill step. For non-power-of-two DPxCP layouts, it falls back to the full DPxCP group if power-of-two expansion cannot fill every rank.

core.datasets.data_schedule_utils.align_sample_id_groups(
sample_id_groups: List,
microbatch_group_size_per_vp_stage: int,
*,
cp_group_sizes: Optional[Sequence[int]] = None,
sample_lengths: Optional[Dict[int, int]] = None,
max_seq_len_per_rank: Optional[int] = None,
pad_sequences: bool = False,
) → List#

Split microbatches for VPP without dropping samples or inventing CP groups.

Expand only through the configured group family, falling back to the full DPxCP group if smaller groups cannot fill a non-power-of-two domain. A full domain group can itself be split when it contains multiple packed samples. Every loop either adds a microbatch/rank or terminates with an explicit error.