DeepSpeedStrategy¶
- class lightning.fabric.strategies.DeepSpeedStrategy(accelerator=None, zero_optimization=True, stage=2, remote_device=None, offload_optimizer=False, offload_parameters=False, offload_params_device='cpu', nvme_path='/local_nvme', params_buffer_count=5, params_buffer_size=100000000, max_in_cpu=1000000000, offload_optimizer_device='cpu', optimizer_buffer_count=4, block_size=1048576, queue_depth=8, single_submit=False, overlap_events=True, thread_count=1, pin_memory=False, sub_group_size=1000000000000, contiguous_gradients=True, overlap_comm=True, allgather_partitions=True, reduce_scatter=True, allgather_bucket_size=200000000, reduce_bucket_size=200000000, zero_allow_untested_optimizer=True, logging_batch_size_per_gpu=None, config=None, logging_level=30, parallel_devices=None, cluster_environment=None, loss_scale=0, initial_scale_power=16, loss_scale_window=1000, hysteresis=2, min_loss_scale=1, partition_activations=False, cpu_checkpointing=False, contiguous_memory_optimization=False, synchronize_checkpoint_boundary=False, load_full_weights=False, precision=None, process_group_backend=None, timeout=datetime.timedelta(seconds=1800))[source]¶
Bases:
DDPStrategy
,_Sharded
Provides capabilities to run training using the DeepSpeed library, with training optimizations for large billion parameter models. For more information: https://pytorch- lightning.readthedocs.io/en/stable/advanced/model_parallel.html#deepspeed.
Warning
This is an experimental feature.
Defaults have been set to enable ZeRO-Offload and some have been taken from the link below. These defaults have been set generally, but may require tuning for optimum performance based on your model size. For more information: https://www.deepspeed.ai/docs/config-json/#zero-optimizations-for-fp16-training.
- Parameters:
zero_optimization¶ (
bool
) – Enable ZeRO optimization. This is compatible with eitherprecision="16-mixed"
orprecision="bf16-mixed"
.stage¶ (
int
) – Different stages of the ZeRO Optimizer. 0 is disabled, 1 is optimizer state partitioning, 2 is optimizer+gradient state partitioning, 3 is optimizer+gradient_parameter partitioning using the infinity engine.remote_device¶ (
Optional
[str
]) – Device to instantiate the model on initially (cpu
ornvme
). Defaults to GPU.offload_optimizer¶ (
bool
) – Enable offloading optimizer memory and computation to CPU or NVMe based onoffload_optimizer_device
.offload_parameters¶ (
bool
) – When using ZeRO Stage 3, Enable offloading parameter memory and computation to CPU or NVMe based onoffload_params_device
.offload_params_device¶ (
str
) – When offloading parameters choose the device to offload to,cpu
ornvme
.offload_optimizer_device¶ (
str
) – When offloading optimizer state choose the device to offload to,cpu
ornvme
.params_buffer_count¶ (
int
) – Number of buffers in buffer pool for parameter offloading whenoffload_params_device
isnvme
.params_buffer_size¶ (
int
) – Size of buffers in buffer pool for parameter offloading whenoffload_params_device
isnvme
.max_in_cpu¶ (
int
) – Number of parameter elements to maintain in CPU memory when offloading to NVMe is enabled.nvme_path¶ (
str
) – Filesystem path for NVMe device for optimizer/parameter state offloading.optimizer_buffer_count¶ (
int
) – Number of buffers in buffer pool for optimizer state offloading whenoffload_optimizer_device
is set to tonvme
. This should be at least the number of states maintained per parameter by the optimizer. For example, Adam optimizer has 4 states (parameter, gradient, momentum, and variance).block_size¶ (
int
) – When using NVMe Offloading, the I/O block size in bytes.queue_depth¶ (
int
) – When using NVMe Offloading, the I/O queue depth.single_submit¶ (
bool
) – When using NVMe Offloading, submit requests to storage device as multiple individual requests, as opposed to one block of requests.overlap_events¶ (
bool
) – When using NVMe Offloading, submit requests to storage device in an overlapped fashion without waiting for completion of earlier requests.thread_count¶ (
int
) – When using NVMe Offloading, Intra-request parallelism for each read/write submitted by a user thread.pin_memory¶ (
bool
) – When using ZeRO stage 3, pin optimizer state memory on CPU. This could boost throughput at the cost of extra memory overhead.sub_group_size¶ (
int
) – When using ZeRO stage 3, defines the number of parameters within a sub group to offload at a time. Smaller numbers require more communication, but improve memory efficiency.contiguous_gradients¶ (
bool
) – Copies gradients to a continuous buffer as they are produced. Avoids memory fragmentation during backwards. Useful when training large models.overlap_comm¶ (
bool
) – Overlap the reduction (synchronization) of gradients with the backwards computation. This is a speed optimization when training across multiple GPUs/machines.allgather_partitions¶ (
bool
) – All gather updated parameters at the end of training step, instead of using a series of broadcast collectives.reduce_scatter¶ (
bool
) – Use reduce/scatter instead of allreduce to average gradients.allgather_bucket_size¶ (
int
) – Number of elements to allgather at once. Used to limit the memory required for larger model sizes, with a tradeoff with speed.reduce_bucket_size¶ (
int
) – Number of elements to reduce at once. Used to limit the memory required for larger model sizes, with a tradeoff with speed.zero_allow_untested_optimizer¶ (
bool
) – Allow untested optimizers to be used with ZeRO. Currently only Adam is a DeepSpeed supported optimizer when using ZeRO.logging_batch_size_per_gpu¶ (
Optional
[int
]) – Config used in DeepSpeed to calculate verbose timing for logging on a per sample per second basis (only displayed if logging=logging.INFO). To obtain accurate logs when using datasets that do not support batch samplers, set this to the actual per gpu batch size.config¶ (
Union
[str
,Path
,dict
[str
,Any
],None
]) – Pass in a deepspeed formatted config dict, or path to a deepspeed config: https://www.deepspeed.ai/docs/config-json. All defaults will be ignored if a config is passed in.loss_scale¶ (
float
) – Loss scaling value for FP16 training. 0.0 results in dynamic loss scaling, otherwise static.initial_scale_power¶ (
int
) – Power of the initial dynamic loss scale value. Loss scale is computed by2^initial_scale_power
.loss_scale_window¶ (
int
) – Window in which to raise/lower the dynamic FP16 loss scaling value.hysteresis¶ (
int
) – FP16 Delay shift in Dynamic Loss scaling.min_loss_scale¶ (
int
) – The minimum FP16 dynamic loss scaling value.partition_activations¶ (
bool
) – Enables partition activation when used with ZeRO stage 3 and model parallelism. Still requires you to wrap your forward functions in deepspeed.checkpointing.checkpoint. See deepspeed tutorial.cpu_checkpointing¶ (
bool
) – Offloads partitioned activations to CPU ifpartition_activations
is enabled.contiguous_memory_optimization¶ (
bool
) – Copies partitioned activations so that they are contiguous in memory. Not supported by all models.synchronize_checkpoint_boundary¶ (
bool
) – Inserttorch.cuda.synchronize()
at each checkpoint boundary.load_full_weights¶ (
bool
) – True when loading a single checkpoint file containing the model state dict when using ZeRO Stage 3. This differs from the DeepSpeed checkpoint which contains shards per worker.
- _initialize_engine(model, optimizer=None)[source]¶
Initialize one model and one optimizer with an optional learning rate scheduler.
This calls
deepspeed.initialize
internally.
- _restore_zero_state(module, ckpt)[source]¶
Overrides the normal load_state_dict behaviour in PyTorch to ensure we gather parameters that may be sharded across processes before loading the state dictionary when using ZeRO stage 3. This is then automatically synced across processes.
- clip_gradients_norm(module, optimizer, max_norm, norm_type=2.0, error_if_nonfinite=True)[source]¶
Clip gradients by norm.
- Return type:
- load_checkpoint(path, state=None, strict=True)[source]¶
Load the contents from a checkpoint and restore the state of the given objects.
- Parameters:
path¶ (
Union
[str
,Path
]) – A path to where the file is locatedstate¶ (
Union
[Module
,Optimizer
,dict
[str
,Union
[Module
,Optimizer
,Any
]],None
]) – A dictionary of objects whose state will be restored in-place from the checkpoint path. This should contain exactly one model, and the model must already be set up by DeepSpeed.strict¶ (
bool
) – Whether to enforce that the keys in state match the keys in the checkpoint.
- Return type:
- Returns:
Dictionary with the state inside DeepSpeed’s engine
- Raises:
ValueError – If no state is provided, when no
deepspeed.DeepSpeedEngine
objects were found in the state, or when multipledeepspeed.DeepSpeedEngine
objects were found.RuntimeError – If DeepSpeed was unable to load the checkpoint due to missing files or because the checkpoint is not in the expected DeepSpeed format.
- module_init_context(empty_init=None)[source]¶
A context manager wrapping the model instantiation.
Here, the strategy can control how the parameters of the model get created (device, dtype) and or apply other patches to the model.
- module_sharded_context()[source]¶
A context manager that goes over the instantiation of an
torch.nn.Module
and handles sharding of parameters on creation.By sharding layers directly on instantiation, one can reduce peak memory usage and initialization time.
- Return type:
- save_checkpoint(path, state, storage_options=None, filter=None)[source]¶
Save model, optimizer, and other state in a checkpoint directory.
- Parameters:
path¶ (
Union
[str
,Path
]) – A path to where the files should be savedstate¶ (
dict
[str
,Union
[Module
,Optimizer
,Any
]]) – A dictionary with contents to be saved. If the dict contains modules or optimizers, their state-dict will be retrieved and converted automatically.storage_options¶ (
Optional
[Any
]) – Unused by this strategy, since it doesn’t use aCheckpointIO
plugin.filter¶ (
Optional
[dict
[str
,Callable
[[str
,Any
],bool
]]]) – Unsupported.
- Raises:
TypeError – If the unused
storage_options
gets passed.ValueError – When no
deepspeed.DeepSpeedEngine
objects were found in the state, or when multipledeepspeed.DeepSpeedEngine
objects were found.
- Return type:
- setup_environment()[source]¶
Setup any processes or distributed connections.
This must be called by the framework at the beginning of every process, before any distributed communication takes place.
- Return type:
- setup_module(module)[source]¶
Set up a module for inference (no optimizers).
For training, see
setup_module_and_optimizers()
.- Return type:
DeepSpeedEngine
- setup_module_and_optimizers(module, optimizers)[source]¶
Set up a model and multiple optimizers together.
Currently, only a single optimizer is supported.
- setup_optimizer(optimizer)[source]¶
Optimizers can only be set up jointly with the model in this strategy.
Please use
setup_module_and_optimizers()
to set up both module and optimizer together.- Return type: