bridge.training.train#
Module Contents#
Functions#
Main training loop. |
|
Single training step. |
|
Synchronizes CUDA streams when the configured interval is reached. |
|
Reports straggler metrics if logging is enabled. |
|
Verifies weight hashes across data-parallel replicas when requested. |
|
Runs manual garbage collection according to the configured interval. |
|
Determine if forward pre-hooks should be disabled during checkpointing. |
|
Enable forward pre-hook for all model chunks. |
|
Disable forward pre-hook for all model chunks. |
|
Force parameter synchronization for all model chunks. |
|
Gets start time of earliest job with same world size. Also returns the number of floating-point operations completed in last saved checkpoint. |
|
Computes job and cumulative throughputs and appends to progress log. |
|
Saves a checkpoint and logs the timing. |
|
Handles checkpointing decisions and determines if training should exit. |
|
Cleanup function called at the end of training. |
|
Return the forward stepβs |
|
Check if the current iteration should be skipped and handle it if so. |
|
Single dummy training step to fast forward train_data_iterator. |
|
Return how many batches this rank reads from its training data iterator on a skipped iteration. |
|
Reject, on every training rank at once, a skipped iteration that a rank cannot perform. |
|
Copy main params to param buffer for mxfp8 with grad buffer reuse. |
|
Release full-iteration graph references without synchronizing CUDA. |
|
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. |
|
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,
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,
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,
Synchronizes CUDA streams when the configured interval is reached.
- Parameters:
train_sync_interval β Number of iterations between synchronizations;
Nonedisables 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,
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.0when 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,
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;
Noneto 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,
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;
0disables 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,
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],
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,
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,
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,
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,
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,
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,
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,
Return the forward stepβs
reads_batch_on_skippolicy, looking throughfunctools.partial.See
ReadsBatchOnSkipfor 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,
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_skippolicy, 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,
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_skippolicy, 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,
Return how many batches this rank reads from its training data iterator on a skipped iteration.
Global-batch packing: TP rank 0 of the first/last pipeline stage reads
num_microbatchessamples for the packing scheduler.dataloader_type="batch": every rank with an iterator reads one global batch, astrain_stepdoes throughprepare_finetuning_batchbefore the forward step runs.Otherwise the forward step reads micro-batches itself.
reads_batch_on_skipsays whether it does on this rank for steps that define it; without it the first and last pipeline stages read. A reading rank readsnum_microbatchesbatches.
- 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,
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],
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:
A fresh runβs first-iteration params are already in param.data from initialization.
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],
- bridge.training.train._release_cuda_graph_references(
- optimizer: megatron.core.optimizer.MegatronOptimizer | 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],
Manually register FSDP communication buffers if enabled.