MixedPrecisionOptimizationStepper#
- class torchrl.trainers.MixedPrecisionOptimizationStepper(optimizer: Optimizer, *, mixed_precision: bool = False, autocast_dtype: dtype = torch.bfloat16, gradient_accumulation_steps: int = 1, clip_norm: float | None = 1.0, device_type: str | None = None)[source]#
Optimization step with mixed precision and gradient accumulation.
This stepper wraps each forward/backward pass in
torch.amp.autocastand optionally scales gradients withtorch.amp.GradScaler(for fp16). It also implements gradient accumulation: gradients are accumulated forgradient_accumulation_stepsmicro-batches before the optimizer is stepped and zeroed.It can be used with any
Trainer; LLM trainers such asGRPOTrainerconstruct it by default.- Parameters:
optimizer (optim.Optimizer) – The optimizer to use.
- Keyword Arguments:
mixed_precision (bool, optional) – Whether to enable mixed-precision training. Default:
False.autocast_dtype (torch.dtype, optional) – The dtype to use inside
autocast. Default:torch.bfloat16.gradient_accumulation_steps (int, optional) – Number of micro-batches over which gradients are accumulated before a step. Default:
1.clip_norm (float, optional) – Maximum gradient norm for clipping. Default:
1.0.device_type (str, optional) – Device type passed to
autocastandGradScaler(e.g."cuda"or"cpu"). Defaults to the device type of the optimizer’s first parameter.
Note
GradScaleris only enabled whenmixed_precision=Trueandautocast_dtype=torch.float16. With bfloat16 (the recommended dtype for modern GPUs) the scaler is a no-op and is not created.- property optimizer_step_count: int#
Number of completed optimizer steps.
Discounts gradient-accumulation micro-steps and steps skipped by the GradScaler on overflow or by the non-finite guards. Read by hooks that act on an optimizer-step cadence (e.g.
UpdateWeightswithinterval_unit="optim_steps").
- register(trainer: Trainer, name: str = 'optimization_stepper') None#
Register the stepper with a Trainer for checkpointing.
- step(trainer: Trainer, sub_batch: TensorDictBase) TensorDictBase[source]#
Perform one forward pass and scaled backward pass.
The optimizer is only stepped and zeroed every
gradient_accumulation_stepscalls.- Parameters:
- Returns:
A
TensorDictwith scalar metrics (losses, grad_norm) suitable for logging.