Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix: Shard batches for evaluation
  • Loading branch information
rrutmann committed May 21, 2026
commit 26fccf9ebf16aebc17cc481e4a4f933a957335dd
12 changes: 12 additions & 0 deletions src/modalities/evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from modalities.models.parallelism.pipeline_parallelism import Pipeline
from modalities.running_env.fsdp.device_mesh import ParallelismDegrees, get_parallel_degree
from modalities.running_env.fsdp.reducer import Reducer
from modalities.trainer import apply_context_parallel_sharding_to_batch
from modalities.util import TimeRecorder


Expand All @@ -33,6 +34,7 @@ def __init__(
"""
self.progress_publisher = progress_publisher
self.evaluation_result_publisher = evaluation_result_publisher
self.device_mesh = device_mesh
if device_mesh is not None:
self.dp_degree = get_parallel_degree(
device_mesh, [ParallelismDegrees.DP_REPLICATE, ParallelismDegrees.DP_SHARD]
Expand Down Expand Up @@ -62,6 +64,16 @@ def evaluate_batch(
torch.Tensor | None: The loss of the batch
None, if a non-last stage was processed in pipeline parallelism
"""
sample_key = getattr(model[0], "sample_key", None)
context_parallel_load_balancer = getattr(model[0], "_context_parallel_load_balancer", "headtail")
apply_context_parallel_sharding_to_batch(
device_mesh=self.device_mesh,
batch=batch,
sample_key=sample_key,
target_key=loss_fun.target_key,
context_parallel_load_balancer=context_parallel_load_balancer,
)

with torch.no_grad():
if scheduled_pipeline is not None:
pp_schedule = scheduled_pipeline.pp_schedule
Expand Down
126 changes: 72 additions & 54 deletions src/modalities/trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,72 @@ class ThroughputAggregationKeys(Enum):
FORWARD_BACKWARD_TIME = "FORWARD_BACKWARD_TIME"


def apply_context_parallel_sharding_to_batch(
device_mesh: DeviceMesh | None,
batch: DatasetBatch,
sample_key: str | None,
target_key: str,
context_parallel_load_balancer: str | None = "headtail",
) -> None:
"""Shard the sequence dimension of a batch in-place for context parallelism.

When a sample_key is provided, also derives and shards ``position_ids`` (global
token positions) so that RotaryTransform receives the correct frequencies for
each CP rank's non-contiguous token range.
"""
if device_mesh is None or not has_parallelism_method(device_mesh, ParallelismDegrees.CP):
return

cp_mesh = get_mesh_for_parallelism_method(device_mesh=device_mesh, parallelism_method=ParallelismDegrees.CP)
if cp_mesh.size() <= 1:
return

buffer_keys: list[tuple[str, str]] = []
buffers: list[torch.Tensor] = []
seq_dims: list[int] = []

if sample_key is not None and sample_key in batch.samples:
if batch.samples[sample_key].device.type != "cuda":
batch.samples[sample_key] = batch.samples[sample_key].to(torch.cuda.current_device(), non_blocking=True)
Comment thread
rrutmann marked this conversation as resolved.
Resolved
# Build global position_ids before sharding so they carry the full-sequence range.
# After HeadTail sharding they hold the correct global indices for each CP rank's
# local tokens, which RotaryTransform uses instead of a local 0-based arange.
full_seq_len = batch.samples[sample_key].shape[1]
position_ids = torch.arange(full_seq_len, device=batch.samples[sample_key].device, dtype=torch.long).unsqueeze(
0
) # (1, T)
buffer_keys.append(("sample", "position_ids"))
buffers.append(position_ids)
seq_dims.append(1)

buffer_keys.append(("sample", sample_key))
buffers.append(batch.samples[sample_key])
seq_dims.append(1)

if target_key in batch.targets:
if batch.targets[target_key].device.type != "cuda":
batch.targets[target_key] = batch.targets[target_key].to(torch.cuda.current_device(), non_blocking=True)
Comment thread
rrutmann marked this conversation as resolved.
Resolved
buffer_keys.append(("target", target_key))
buffers.append(batch.targets[target_key])
seq_dims.append(1)

if not buffers:
return

sharded_buffers = shard_tensor_buffers_for_context_parallel(
cp_mesh=cp_mesh,
buffers=tuple(buffers),
seq_dims=tuple(seq_dims),
load_balancer_type=context_parallel_load_balancer,
)

for (kind, key), tensor in zip(buffer_keys, sharded_buffers, strict=True):
if kind == "sample":
batch.samples[key] = tensor
else:
batch.targets[key] = tensor


class Trainer:
def __init__(
self,
Expand Down Expand Up @@ -140,62 +206,14 @@ def _apply_context_parallel_sharding_to_batch_(
target_key: str,
context_parallel_load_balancer: str | None = "headtail",
) -> None:
if self.device_mesh is None or not has_parallelism_method(self.device_mesh, ParallelismDegrees.CP):
return

cp_mesh = get_mesh_for_parallelism_method(
device_mesh=self.device_mesh, parallelism_method=ParallelismDegrees.CP
)
if cp_mesh.size() <= 1:
return

buffer_keys: list[tuple[str, str]] = []
buffers: list[torch.Tensor] = []
seq_dims: list[int] = []

if sample_key is not None and sample_key in batch.samples:
if batch.samples[sample_key].device.type != "cuda":
batch.samples[sample_key] = batch.samples[sample_key].to(torch.cuda.current_device(), non_blocking=True)
# Build global position_ids before sharding so they carry the full-sequence range.
# After HeadTail sharding they hold the correct global indices for each CP rank's
# local tokens, which RotaryTransform uses instead of a local 0-based arange.
full_seq_len = batch.samples[sample_key].shape[1]
position_ids = torch.arange(
full_seq_len, device=batch.samples[sample_key].device, dtype=torch.long
).unsqueeze(
0
) # (1, T)
buffer_keys.append(("sample", "position_ids"))
buffers.append(position_ids)
seq_dims.append(1)

buffer_keys.append(("sample", sample_key))
buffers.append(batch.samples[sample_key])
seq_dims.append(1)

if target_key in batch.targets:
if batch.targets[target_key].device.type != "cuda":
batch.targets[target_key] = batch.targets[target_key].to(torch.cuda.current_device(), non_blocking=True)
buffer_keys.append(("target", target_key))
buffers.append(batch.targets[target_key])
seq_dims.append(1)

if not buffers:
return

sharded_buffers = shard_tensor_buffers_for_context_parallel(
cp_mesh=cp_mesh,
buffers=tuple(buffers),
seq_dims=tuple(seq_dims),
load_balancer_type=context_parallel_load_balancer,
apply_context_parallel_sharding_to_batch(
device_mesh=self.device_mesh,
batch=batch,
sample_key=sample_key,
target_key=target_key,
context_parallel_load_balancer=context_parallel_load_balancer,
)

for (kind, key), tensor in zip(buffer_keys, sharded_buffers, strict=True):
if kind == "sample":
batch.samples[key] = tensor
else:
batch.targets[key] = tensor

def _train_batch(
self,
batch: DatasetBatch,
Expand Down
Loading