MixedPrecision

class lightning.fabric.plugins.precision.MixedPrecision(precision, device, scaler=None)[source]

Bases: Precision

Plugin for Automatic Mixed Precision (AMP) training with torch.autocast.

Parameters:
  • precision (Literal['16-mixed', 'bf16-mixed']) – Whether to use torch.float16 ('16-mixed') or torch.bfloat16 ('bf16-mixed').

  • device (str) – The device for torch.autocast.

  • scaler (Optional[GradScaler]) – An optional torch.cuda.amp.GradScaler to use.

backward(tensor, model, *args, **kwargs)[source]

Performs the actual backpropagation.

Parameters:
  • tensor (Tensor) – The tensor that will be used for backpropagation

  • model (Optional[Module]) – The module that was involved in producing the tensor and whose parameters need the gradients

Return type:

None

convert_input(data)[source]

Convert model inputs (forward) to the floating point precision type of this plugin.

This is a no-op in the base precision plugin, since we assume the data already has the desired type (default is torch.float32).

Return type:

Any

convert_output(data)[source]

Convert outputs to the floating point precision type expected after model’s forward.

This is a no-op in the base precision plugin, since we assume the data already has the desired type (default is torch.float32).

Return type:

Any

forward_context()[source]

A contextmanager for managing model forward/training_step/evaluation_step/predict_step.

Return type:

ContextManager

load_state_dict(state_dict)[source]

Called when loading a checkpoint, implement to reload precision plugin state given precision plugin state_dict.

Parameters:

state_dict (Dict[str, Any]) – the precision plugin state returned by state_dict.

Return type:

None

optimizer_step(optimizer, **kwargs)[source]

Hook to run the optimizer step.

Return type:

Any

state_dict()[source]

Called when saving a checkpoint, implement to generate precision plugin state_dict.

Return type:

Dict[str, Any]

Returns:

A dictionary containing precision plugin state.