Args:
stage: Local chunk about to execute forward.
micro_index: Microbatch index within the current optimizer step.
"""
trainer = self.trainer
if stage is self.stages[0]:
inputs, loss_inputs = next(self.batches)
inputs, loss_inputs = trainer.preforward(inputs), trainer.preforward(loss_inputs)
counts = count_loss_token(loss_inputs)
for name, value in counts.items():
trainer.step_token_counts[name] = trainer.step_token_counts.get(name, 0) + value.detach()
count = counts["foundation_tokens"]
trainer.on_micro_step_begin({**inputs, **loss_inputs, "token_count": count})
trainer.begin_fsdp_runtime_diagnostics(micro_index)
mesh = trainer.mesh
if mesh.sequence_parallel:
group = mesh.device_mesh["tp"].get_group()
count = count.clone()
dist.all_reduce(count, group=group)
count = count / dist.get_world_size(group)
self.batch_cache[micro_index] = (inputs, loss_inputs, counts, count * mesh.dp_size * mesh.cp_size)
if stage is self.stages[-1]:
return self.batch_cache.pop(micro_index)
return self.batch_cache[micro_index]
def _load_visual_input(self, step, context):
context.arg_mbs[step.micro_index] = self.visual_inputs.pop(step.micro_index)
def _finish_step(self, losses: list, count: int) -> tuple[float, dict[str, float]]:
"""Publish per-microbatch callbacks and the same step numerators on every stage."""
trainer = self.trainer
group = trainer.mesh.pp_mesh.get_group()
source = trainer.mesh.pp_mesh.rank_list[-1]
keys = [tuple(self.metrics[i]) for i in range(count)] if self.partition.is_last else None
metadata = [(keys, trainer.loss_names) if self.partition.is_last else None]
dist.broadcast_object_list(metadata, src=source, group=group)
keys, trainer.loss_names = metadata[0]
columns = {name: i for i, name in enumerate(dict.fromkeys(name for row in keys for name in row), start=1)}
values = torch.zeros((count, len(columns) + 1), device=trainer.device, dtype=torch.float32)
if self.partition.is_last:
values[:, 0] = torch.stack(losses).detach()
for i, metrics in self.metrics.items():
for name, value in metrics.items():
values[i, columns[name]] = value
dist.broadcast(values, src=source, group=group)
dist.all_reduce(self.router_stats, group=group)
router_counts = self.router_stats[:, 1].tolist()
totals = defaultdict(float)
for i, names in enumerate(keys):
metrics = {name: values[i, columns[name]] for name in names}
if router_counts[i]:
metrics["router_aux_loss"] = self.router_stats[i, 0] / router_counts[i]
trainer.on_micro_step_end(metrics)
for name, value in metrics.items():
totals[name] += value.item()
return sum(values[:, 0].tolist()), totals
def run(self, batches: Iterator[tuple[dict, dict]], count: int) -> tuple[float, dict[str, float]]:
"""Consume batches in forward order and schedule their forward/backward work.