bridge.training.train#

Module Contents#

Functions#

train

Main training loop.

train_step

Single training step.

maybe_synchronize_training_step

Synchronizes CUDA streams when the configured interval is reached.

maybe_report_stragglers

Reports straggler metrics if logging is enabled.

maybe_check_weight_hash_across_dp_replicas

Verifies weight hashes across data-parallel replicas when requested.

maybe_run_manual_gc

Runs manual garbage collection according to the configured interval.

should_disable_forward_pre_hook

Determine if forward pre-hooks should be disabled during checkpointing.

enable_forward_pre_hook

Enable forward pre-hook for all model chunks.

disable_forward_pre_hook

Disable forward pre-hook for all model chunks.

force_param_sync

Force parameter synchronization for all model chunks.

get_start_time_from_progress_log

Gets start time of earliest job with same world size. Also returns the number of floating-point operations completed in last saved checkpoint.

compute_throughputs_and_append_to_progress_log

Computes job and cumulative throughputs and appends to progress log.

save_checkpoint_and_time

Saves a checkpoint and logs the timing.

checkpoint_and_decide_exit

Handles checkpointing decisions and determines if training should exit.

_finish_train

Cleanup function called at the end of training.

_resolve_reads_batch_on_skip

Return the forward step’s reads_batch_on_skip policy, looking through functools.partial.

_should_skip_and_handle_iteration

Check if the current iteration should be skipped and handle it if so.

_dummy_train_step

Single dummy training step to fast forward train_data_iterator.

_num_batches_read_on_skip

Return how many batches this rank reads from its training data iterator on a skipped iteration.

_check_skip_can_advance_train_data_iterator

Reject, on every training rank at once, a skipped iteration that a rank cannot perform.

_handle_mxfp8_param_buffer_copy

Copy main params to param buffer for mxfp8 with grad buffer reuse.

_delete_local_cuda_graph_runners

_release_cuda_graph_references

Release full-iteration graph references without synchronizing CUDA.

_delete_cuda_graphs

Delete the CUDA graph object as they hold a reference to the some of the nccl buffers, thus blocking the process-destory (torch.dist.destroy_process_group()) at the end of the training loop.

_maybe_register_fsdp_buffers

Manually register FSDP communication buffers if enabled.

API#

bridge.training.train.train(
forward_step_func: megatron.bridge.training.forward_step_func_types.ForwardStepCallable,
model: list[megatron.core.transformer.MegatronModule],
optimizer: megatron.core.optimizer.MegatronOptimizer,
scheduler: megatron.core.optimizer_param_scheduler.OptimizerParamScheduler,
train_data_iterator: Optional[Union[megatron.core.rerun_state_machine.RerunDataIterator, list[megatron.core.rerun_state_machine.RerunDataIterator]]],
valid_data_iterator: Optional[Union[megatron.core.rerun_state_machine.RerunDataIterator, list[megatron.core.rerun_state_machine.RerunDataIterator]]],
global_state: megatron.bridge.training.state.GlobalState,
checkpoint_manager: megatron.bridge.training.checkpointing.CheckpointManager,
pg_collection: megatron.core.process_groups_config.ProcessGroupCollection,
process_non_loss_data_func: Optional[Callable] = None,
non_loss_data_func: Optional[Callable] = None,
callback_manager: megatron.bridge.training.callbacks.CallbackManager | None = None,
) → None#

Main training loop.

Handles the overall training process, including the iteration loop, calling train_step, evaluation, checkpointing, logging, and exit conditions.

Parameters:
  • forward_step_func – Callable that executes a single forward step.

  • model – list of model chunks (potentially wrapped in DDP).

  • optimizer – The optimizer instance.

  • scheduler – The learning rate scheduler instance.

  • train_data_iterator – Iterator for the training dataset.

  • valid_data_iterator – Iterator for the validation dataset.

  • global_state – The GlobalState object holding various training states.

  • checkpoint_manager – The checkpoint manager for save/load operations.

  • process_non_loss_data_func – Optional function to process non-loss data during evaluation.

  • non_loss_data_func – Optional function to compute non-loss data during evaluation.

  • callback_manager – Optional CallbackManager for custom callback execution.

.. warning::

This is an experimental API and is subject to change in backwards incompatible ways without notice.

bridge.training.train.train_step(
forward_step_func: megatron.bridge.training.forward_step_func_types.ForwardStepCallable,
data_iterator: Optional[Union[megatron.core.rerun_state_machine.RerunDataIterator, list[megatron.core.rerun_state_machine.RerunDataIterator]]],
model: list[megatron.core.transformer.MegatronModule],
optimizer: megatron.core.optimizer.MegatronOptimizer,
scheduler: megatron.core.optimizer_param_scheduler.OptimizerParamScheduler,
global_state: megatron.bridge.training.state.GlobalState,
pg_collection: megatron.core.process_groups_config.ProcessGroupCollection,
forward_backward_func: Callable,
p2p_communicator: megatron.core.pipeline_parallel.p2p_communication.P2PCommunicator,
) → tuple[dict[str, torch.Tensor], int, bool, bool, int, Optional[float], Optional[int]]#

Single training step.

Parameters:
  • forward_step_func – Function that performs a forward step (already wrapped if needed)

  • data_iterator – Iterator over training data

  • model – list of model chunks

  • optimizer – Optimizer for model parameters

  • scheduler – Learning rate scheduler

  • global_state – Global training state

  • pg_collection – Process group collection

  • forward_backward_func – forward-backward function

Returns:

  • loss_dict: Dictionary of reduced losses

  • skipped_iter: Whether the iteration was skipped (1) or not (0)

  • should_checkpoint: Whether a checkpoint should be saved

  • should_exit: Whether training should exit

  • exit_code: Exit code if should_exit is True

  • grad_norm: Gradient norm if available, None otherwise

  • num_zeros_in_grad: Number of zeros in gradient if available, None otherwise

  • max_attention_logit: Maximum attention logit if available, None otherwise

Return type:

tuple containing

bridge.training.train.maybe_synchronize_training_step(
train_sync_interval: Optional[int],
iteration: int,
) → None#

Synchronizes CUDA streams when the configured interval is reached.

Parameters:
  • train_sync_interval – Number of iterations between synchronizations; None disables it.

  • iteration – Zero-based training iteration counter.

bridge.training.train.maybe_report_stragglers(
log_interval: int,
log_straggler: bool,
straggler_timer: Any,
iteration: int,
num_floating_point_operations_since_last_log_event: float,
) → float#

Reports straggler metrics if logging is enabled.

Parameters:
  • log_interval – Iteration interval for logging.

  • log_straggler – Whether straggler logging is enabled.

  • straggler_timer – Timer utility used to record straggler metrics.

  • iteration – Zero-based training iteration counter.

  • num_floating_point_operations_since_last_log_event – FLOPs accumulated since the last logging event.

Returns:

Updated FLOP counter, reset to 0.0 when a report is emitted; otherwise the original value.

Return type:

float

bridge.training.train.maybe_check_weight_hash_across_dp_replicas(
model: list[megatron.core.transformer.MegatronModule],
optimizer: Optional[megatron.core.optimizer.MegatronOptimizer],
check_weight_hash_across_dp_replicas_interval: Optional[int],
iteration: int,
should_toggle_forward_pre_hook: bool,
) → None#

Verifies weight hashes across data-parallel replicas when requested.

Parameters:
  • model – List of model chunks to validate.

  • optimizer – Optimizer used to stage params before disabling the pre-hook.

  • check_weight_hash_across_dp_replicas_interval – Interval at which to verify; None to skip.

  • iteration – Zero-based training iteration counter.

  • should_toggle_forward_pre_hook – Whether the pre-hook must be disabled during the check.

bridge.training.train.maybe_run_manual_gc(
manual_gc_enabled: bool,
manual_gc_interval: int,
iteration: int,
) → None#

Runs manual garbage collection according to the configured interval.

Parameters:
  • manual_gc_enabled – Whether manual garbage collection is enabled.

  • manual_gc_interval – Number of iterations between collections; 0 disables periodic runs.

  • iteration – Zero-based training iteration counter.

bridge.training.train.should_disable_forward_pre_hook(
use_megatron_fsdp: bool,
use_distributed_optimizer: bool,
overlap_param_gather: bool,
) → bool#

Determine if forward pre-hooks should be disabled during checkpointing.

Forward pre-hooks need to be disabled during checkpoint saving when using distributed optimizer with overlapped parameter gathering

Parameters:
  • use_megatron_fsdp – Whether Megatron FSDP is enabled.

  • use_distributed_optimizer – Whether distributed optimizer is enabled.

  • overlap_param_gather – Whether parameter gathering is overlapped.

Returns:

True if forward pre-hooks should be disabled, False otherwise.

.. note::

This is needed to prevent autograd issues during checkpoint saving when using distributed optimizer with parameter gathering overlap.

bridge.training.train.enable_forward_pre_hook(
model: list[megatron.core.distributed.DistributedDataParallel],
) → None#

Enable forward pre-hook for all model chunks.

Parameters:

model – list of model chunks wrapped in DDP

bridge.training.train.disable_forward_pre_hook(
model: list[megatron.core.distributed.DistributedDataParallel],
optimizer: Optional[megatron.core.optimizer.MegatronOptimizer] = None,
param_sync: bool = True,
) → None#

Disable forward pre-hook for all model chunks.

Parameters:
  • model – list of model chunks wrapped in DDP

  • optimizer – Optional optimizer used to stage params before forced sync.

  • param_sync – Whether to synchronize parameters across model chunks

bridge.training.train.force_param_sync(
model: list[megatron.core.transformer.MegatronModule],
optimizer: Optional[megatron.core.optimizer.MegatronOptimizer] = None,
) → None#

Force parameter synchronization for all model chunks.

Parameters:
  • model – Model chunks implementing start_param_sync, directly or through a wrapper.

  • optimizer – Optional optimizer used to stage params before forced sync.

bridge.training.train.get_start_time_from_progress_log(
cfg: megatron.bridge.training.config.ConfigContainer,
) → tuple[datetime.datetime, float]#

Gets start time of earliest job with same world size. Also returns the number of floating-point operations completed in last saved checkpoint.

bridge.training.train.compute_throughputs_and_append_to_progress_log(
state: megatron.bridge.training.state.GlobalState,
num_floating_point_operations_so_far: float,
) → None#

Computes job and cumulative throughputs and appends to progress log.

Calculates Model TFLOP/s/GPU based on floating-point operations and elapsed time. Appends the computed throughputs, total FLOPs, and processed tokens to the progress log file.

Parameters:
  • state – The GlobalState object.

  • num_floating_point_operations_so_far – Total floating-point operations completed.

bridge.training.train.save_checkpoint_and_time(
state: megatron.bridge.training.state.GlobalState,
model: list[megatron.core.transformer.MegatronModule],
optimizer: megatron.core.optimizer.MegatronOptimizer,
opt_param_scheduler: megatron.core.optimizer_param_scheduler.OptimizerParamScheduler,
num_floating_point_operations_so_far: float,
checkpoint_manager: megatron.bridge.training.checkpointing.CheckpointManager,
non_persistent_ckpt: bool = False,
train_data_iterator: Optional[Union[megatron.core.rerun_state_machine.RerunDataIterator, list[megatron.core.rerun_state_machine.RerunDataIterator]]] = None,
pg_collection: Optional[megatron.core.process_groups_config.ProcessGroupCollection] = None,
callback_manager: Optional[megatron.bridge.training.callbacks.CallbackManager] = None,
module_name: str | None = None,
) → None#

Saves a checkpoint and logs the timing.

Wraps the checkpoint manager’s save method with timers and forces parameter synchronization when using distributed optimizer with overlapped parameter gather to ensure checkpoint correctness.

Parameters:
  • state – The global state object.

  • model – list of model chunks (MegatronModule instances).

  • optimizer – The optimizer instance.

  • opt_param_scheduler – The optimizer parameter scheduler instance.

  • num_floating_point_operations_so_far – Cumulative Model TFLOPs up to this point.

  • checkpoint_manager – The checkpoint manager for save operations.

  • non_persistent_ckpt – Flag indicating if this is a non-persistent (local) checkpoint. Defaults to False.

  • train_data_iterator – Optional training data iterator to save its state.

  • pg_collection – Optional process group collection for MegatronMIMO topologies. When None, save_checkpoint falls back to model-attached PGs.

bridge.training.train.checkpoint_and_decide_exit(
state: megatron.bridge.training.state.GlobalState,
model: list[megatron.core.transformer.MegatronModule],
optimizer: megatron.core.optimizer.MegatronOptimizer,
opt_param_scheduler: megatron.core.optimizer_param_scheduler.OptimizerParamScheduler,
num_floating_point_operations_so_far: float,
checkpoint_manager: megatron.bridge.training.checkpointing.CheckpointManager,
train_data_iterator: Optional[Union[megatron.core.rerun_state_machine.RerunDataIterator, list[megatron.core.rerun_state_machine.RerunDataIterator]]],
pg_collection: Optional[megatron.core.process_groups_config.ProcessGroupCollection] = None,
callback_manager: Optional[megatron.bridge.training.callbacks.CallbackManager] = None,
module_name: str | None = None,
) → bool#

Handles checkpointing decisions and determines if training should exit.

Checks various conditions for saving a checkpoint (signal received, interval, duration) and determines if the training loop should terminate based on exit conditions (signal, duration, iteration interval).

Parameters:
  • state – The global state object.

  • model – list of model chunks (MegatronModule instances).

  • optimizer – The optimizer instance.

  • opt_param_scheduler – The optimizer parameter scheduler instance.

  • num_floating_point_operations_so_far – Cumulative TFLOPs up to this point.

  • checkpoint_manager – The checkpoint manager for save operations.

  • train_data_iterator – Optional training data iterator to save its state.

  • pg_collection – Optional process group collection for MegatronMIMO topologies. When None, save_checkpoint falls back to model-attached PGs.

Returns:

True if the training loop should exit, False otherwise.

bridge.training.train._finish_train(
global_state: megatron.bridge.training.state.GlobalState,
checkpoint_manager: megatron.bridge.training.checkpointing.CheckpointManager,
)#

Cleanup function called at the end of training.

Parameters:
  • global_state – The global training state.

  • checkpoint_manager – The checkpoint manager for finalizing async saves.

bridge.training.train._resolve_reads_batch_on_skip(
forward_step_func: megatron.bridge.training.forward_step_func_types.ForwardStepCallable,
) → megatron.bridge.training.forward_step_func_types.ReadsBatchOnSkip | None#

Return the forward step’s reads_batch_on_skip policy, looking through functools.partial.

See ReadsBatchOnSkip for the lookup order.

bridge.training.train._should_skip_and_handle_iteration(
global_state: megatron.bridge.training.state.GlobalState,
train_data_iterator: Optional[Union[megatron.core.rerun_state_machine.RerunDataIterator, list[megatron.core.rerun_state_machine.RerunDataIterator]]],
pg_collection: megatron.core.process_groups_config.ProcessGroupCollection,
*,
reads_batch_on_skip: megatron.bridge.training.forward_step_func_types.ReadsBatchOnSkip | None = None,
) → bool#

Check if the current iteration should be skipped and handle it if so.

This function checks if the current training step is in the iterations_to_skip list, and if so, performs a dummy training step to consume data and update counters.

Parameters:
  • global_state – Global state containing training state and configuration

  • train_data_iterator – Iterator over training data

  • pg_collection – Process groups of this rank

  • reads_batch_on_skip – The forward step’s reads_batch_on_skip policy, if it has one

Returns:

True if the iteration was skipped, False otherwise

Return type:

bool

bridge.training.train._dummy_train_step(
global_state: megatron.bridge.training.state.GlobalState,
train_data_iterator: Optional[Union[megatron.core.rerun_state_machine.RerunDataIterator, list[megatron.core.rerun_state_machine.RerunDataIterator]]],
pg_collection: megatron.core.process_groups_config.ProcessGroupCollection,
*,
reads_batch_on_skip: megatron.bridge.training.forward_step_func_types.ReadsBatchOnSkip | None = None,
) → None#

Single dummy training step to fast forward train_data_iterator.

This function consumes data from the iterator without performing any actual computation, effectively skipping the iteration while maintaining data iterator consistency. The rank reads what a real iteration would read from the iterator (see _num_batches_read_on_skip).

Parameters:
  • global_state – Global state containing configuration

  • train_data_iterator – Iterator over training data

  • pg_collection – Process groups of this rank

  • reads_batch_on_skip – The forward step’s reads_batch_on_skip policy, if it has one

bridge.training.train._num_batches_read_on_skip(
cfg: megatron.bridge.training.config.ConfigContainer,
pg_collection: megatron.core.process_groups_config.ProcessGroupCollection,
reads_batch_on_skip: megatron.bridge.training.forward_step_func_types.ReadsBatchOnSkip | None,
) → int#

Return how many batches this rank reads from its training data iterator on a skipped iteration.

  1. Global-batch packing: TP rank 0 of the first/last pipeline stage reads num_microbatches samples for the packing scheduler.

  2. dataloader_type="batch": every rank with an iterator reads one global batch, as train_step does through prepare_finetuning_batch before the forward step runs.

  3. Otherwise the forward step reads micro-batches itself. reads_batch_on_skip says whether it does on this rank for steps that define it; without it the first and last pipeline stages read. A reading rank reads num_microbatches batches.

bridge.training.train._check_skip_can_advance_train_data_iterator(
cfg: megatron.bridge.training.config.ConfigContainer,
train_data_iterator: Optional[Union[megatron.core.rerun_state_machine.RerunDataIterator, list[megatron.core.rerun_state_machine.RerunDataIterator]]],
pg_collection: megatron.core.process_groups_config.ProcessGroupCollection,
*,
reads_batch_on_skip: megatron.bridge.training.forward_step_func_types.ReadsBatchOnSkip | None,
) → None#

Reject, on every training rank at once, a skipped iteration that a rank cannot perform.

A skipped iteration reads from one training data iterator. It cannot advance a caller-supplied list of per-model-chunk iterators, because it does not know how many batches each chunk would read. Every rank reaches the same skipped iteration, reports whether it would read while holding such a list, and all ranks raise if any does, before any of them reads a batch or updates the skip counters.

Raises:

ValueError – If any rank would have to advance a list of per-model-chunk iterators.

bridge.training.train._handle_mxfp8_param_buffer_copy(
optimizer: megatron.core.optimizer.MegatronOptimizer,
model: list[megatron.core.transformer.MegatronModule],
) → None#

Copy main params to param buffer for mxfp8 with grad buffer reuse.

For mxfp8_param with reuse_grad_buf_for_mxfp8_param_ag and dp_ag_overlap, we need to call _copy_main_params_to_param_buffer() after the grad buffer is zeroed because param and grad buffer are shared.

However, we should skip this on the first iteration when forward_pre_hook is disabled, because:

  1. A fresh run’s first-iteration params are already in param.data from initialization.

  2. Without forward_pre_hook, finish_param_sync() won’t be called to zero the grad buffer, so the main grads will be polluted by the main params.

Exception: when a full-iteration CUDA graph has been captured, the all-gather and subsequent param_data zero are baked into the graph and replay unconditionally. We must populate param_data so the replayed AG gathers correct weights, even when forward pre-hooks are disabled (first iteration).

Parameters:
  • optimizer – The MegatronOptimizer instance

  • model – List of model chunks (MegatronModule instances)

bridge.training.train._delete_local_cuda_graph_runners(
model: list[megatron.core.transformer.MegatronModule],
) → None#
bridge.training.train._release_cuda_graph_references(
optimizer: megatron.core.optimizer.MegatronOptimizer | None,
) → None#

Release full-iteration graph references without synchronizing CUDA.

bridge.training.train._delete_cuda_graphs(
cuda_graph_helper: megatron.core.transformer.cuda_graphs.TECudaGraphHelper | None,
model: list[megatron.core.transformer.MegatronModule] | None = None,
optimizer: megatron.core.optimizer.MegatronOptimizer | None = None,
)#

Delete the CUDA graph object as they hold a reference to the some of the nccl buffers, thus blocking the process-destory (torch.dist.destroy_process_group()) at the end of the training loop.

TODO: Move this method to MCore.

Parameters:
  • cuda_graph_helper – The TECudaGraphHelper object.

  • model – The list of model chunks (MegatronModule instances).

  • optimizer – Optimizer whose gradient conversion may retain the training graph.

bridge.training.train._maybe_register_fsdp_buffers(
config: megatron.bridge.training.config.ConfigContainer,
model: list[megatron.core.transformer.MegatronModule],
) → None#

Manually register FSDP communication buffers if enabled.