Debian Codegraph @

docs/source/usage_guides/deepspeed.md

raw
1 <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4 the License. You may obtain a copy of the License at
5
6 http://www.apache.org/licenses/LICENSE-2.0
7
8 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9 an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10 specific language governing permissions and limitations under the License.
11
12 ⚠️ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
13 rendered properly in your Markdown viewer.
14 -->
15
16 # DeepSpeed
17
18 [DeepSpeed](https://github.com/deepspeedai/DeepSpeed) implements everything described in the [ZeRO paper](https://huggingface.co/papers/1910.02054). Some of the salient optimizations are:
19
20 1. Optimizer state partitioning (ZeRO stage 1)
21 2. Gradient partitioning (ZeRO stage 2)
22 3. Parameter partitioning (ZeRO stage 3)
23 4. Custom mixed precision training handling
24 5. A range of fast CUDA-extension-based optimizers
25 6. ZeRO-Offload to CPU and Disk/NVMe
26 7. Hierarchical partitioning of model parameters (ZeRO++)
27
28 ZeRO-Offload has its own dedicated paper: [ZeRO-Offload: Democratizing Billion-Scale Model Training](https://huggingface.co/papers/2101.06840). And NVMe-support is described in the paper [ZeRO-Infinity: Breaking the GPU
29 Memory Wall for Extreme Scale Deep Learning](https://huggingface.co/papers/2104.07857).
30
31 DeepSpeed ZeRO-2 is primarily used only for training, as its features are of no use to inference.
32
33 DeepSpeed ZeRO-3 can be used for inference as well since it allows huge models to be loaded on multiple GPUs, which
34 won't be possible on a single GPU.
35
36 Accelerate integrates [DeepSpeed](https://github.com/deepspeedai/DeepSpeed) via 2 options:
37
38 1. Integration of the DeepSpeed features via `deepspeed config file` specification in `accelerate config` . You just supply your custom config file or use our template. Most of
39 this document is focused on this feature. This supports all the core features of DeepSpeed and gives user a lot of flexibility.
40 User may have to change a few lines of code depending on the config.
41 2. Integration via `deepspeed_plugin`.This supports subset of the DeepSpeed features and uses default options for the rest of the configurations.
42 User need not change any code and is good for those who are fine with most of the default settings of DeepSpeed.
43
44 ## What is integrated?
45
46 Training:
47
48 1. Accelerate integrates all features of DeepSpeed ZeRO. This includes all the ZeRO stages 1, 2 and 3 as well as ZeRO-Offload, ZeRO-Infinity (which can offload to disk/NVMe) and ZeRO++.
49 Below is a short description of Data Parallelism using ZeRO - Zero Redundancy Optimizer along with diagram from this [blog post](https://www.microsoft.com/en-us/research/blog/zero-deepspeed-new-system-optimizations-enable-training-models-with-over-100-billion-parameters/)
50 ![ZeRO Data Parallelism](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/parallelism-zero.png)
51
52 (Source: [link](https://www.microsoft.com/en-us/research/blog/zero-deepspeed-new-system-optimizations-enable-training-models-with-over-100-billion-parameters/))
53
54 a. **Stage 1** : Shards optimizer states across data parallel workers/GPUs
55
56 b. **Stage 2** : Shards optimizer states + gradients across data parallel workers/GPUs
57
58 c. **Stage 3**: Shards optimizer states + gradients + model parameters across data parallel workers/GPUs
59
60 d. **Optimizer Offload**: Offloads the gradients + optimizer states to CPU/Disk building on top of ZERO Stage 2
61
62 e. **Param Offload**: Offloads the model parameters to CPU/Disk building on top of ZERO Stage 3
63
64 f. **Hierarchical Partitioning**: Enables efficient multi-node training with data-parallel training across nodes and ZeRO-3 sharding within a node, built on top of ZeRO Stage 3.
65
66 <u>Note</u>: With respect to Disk Offload, the disk should be an NVME for decent speed but it technically works on any Disk
67
68 Inference:
69
70 1. DeepSpeed ZeRO Inference supports ZeRO stage 3 with ZeRO-Infinity. It uses the same ZeRO protocol as training, but
71 it doesn't use an optimizer and a lr scheduler and only stage 3 is relevant. For more details see:
72 [deepspeed-zero-inference](#deepspeed-zero-inference).
73
74
75 ## How it works?
76
77 **Pre-Requisites**: Install DeepSpeed version >=0.6.5. Please refer to the [DeepSpeed Installation details](https://github.com/deepspeedai/DeepSpeed#installation)
78 for more information.
79
80 We will first look at easy to use integration via `accelerate config`.
81 Followed by more flexible and feature rich `deepspeed config file` integration.
82
83 ### Accelerate DeepSpeed Plugin
84 On your machine(s) just run:
85
86 ```bash
87 accelerate config
88 ```
89
90 and answer the questions asked. It will ask whether you want to use a config file for DeepSpeed to which you should answer no. Then answer the following questions to generate a basic DeepSpeed config.
91 This will generate a config file that will be used automatically to properly set the
92 default options when doing
93
94 ```bash
95 accelerate launch my_script.py --args_to_my_script
96 ```
97
98 For instance, here is how you would run the NLP example `examples/nlp_example.py` (from the root of the repo) with DeepSpeed Plugin:
99
100 **ZeRO Stage-2 DeepSpeed Plugin Example**
101 ```bash
102 compute_environment: LOCAL_MACHINE
103 deepspeed_config:
104 gradient_accumulation_steps: 1
105 gradient_clipping: 1.0
106 offload_optimizer_device: none
107 offload_param_device: none
108 zero3_init_flag: true
109 zero_stage: 2
110 distributed_type: DEEPSPEED
111 fsdp_config: {}
112 machine_rank: 0
113 main_process_ip: null
114 main_process_port: null
115 main_training_function: main
116 mixed_precision: fp16
117 num_machines: 1
118 num_processes: 2
119 use_cpu: false
120 ```
121
122 ```bash
123 accelerate launch examples/nlp_example.py --mixed_precision fp16
124 ```
125
126 **ZeRO Stage-3 with CPU Offload DeepSpeed Plugin Example**
127 ```bash
128 compute_environment: LOCAL_MACHINE
129 deepspeed_config:
130 gradient_accumulation_steps: 1
131 gradient_clipping: 1.0
132 offload_optimizer_device: cpu
133 offload_param_device: cpu
134 zero3_init_flag: true
135 zero3_save_16bit_model: true
136 zero_stage: 3
137 distributed_type: DEEPSPEED
138 fsdp_config: {}
139 machine_rank: 0
140 main_process_ip: null
141 main_process_port: null
142 main_training_function: main
143 mixed_precision: fp16
144 num_machines: 1
145 num_processes: 2
146 use_cpu: false
147 ```
148
149 ```bash
150 accelerate launch examples/nlp_example.py --mixed_precision fp16
151 ```
152
153 Currently, `Accelerate` supports following config through the CLI:
154
155 ```bash
156 `zero_stage`: [0] Disabled, [1] optimizer state partitioning, [2] optimizer+gradient state partitioning and [3] optimizer+gradient+parameter partitioning
157 `gradient_accumulation_steps`: Number of training steps to accumulate gradients before averaging and applying them.
158 `gradient_clipping`: Enable gradient clipping with value.
159 `offload_optimizer_device`: [none] Disable optimizer offloading, [cpu] offload optimizer to CPU, [nvme] offload optimizer to NVMe SSD. Only applicable with ZeRO >= Stage-2.
160 `offload_optimizer_nvme_path`: Decides Nvme Path to offload optimizer states. If unspecified, will default to 'none'.
161 `offload_param_device`: [none] Disable parameter offloading, [cpu] offload parameters to CPU, [nvme] offload parameters to NVMe SSD. Only applicable with ZeRO Stage-3.
162 `offload_param_nvme_path`: Decides Nvme Path to offload parameters. If unspecified, will default to 'none'.
163 `zero3_init_flag`: Decides whether to enable `deepspeed.zero.Init` for constructing massive models. Only applicable with ZeRO Stage-3.
164 `zero3_save_16bit_model`: Decides whether to save 16-bit model weights when using ZeRO Stage-3.
165 `mixed_precision`: `no` for FP32 training, `fp16` for FP16 mixed-precision training and `bf16` for BF16 mixed-precision training.
166 `deepspeed_moe_layer_cls_names`: Comma-separated list of transformer Mixture-of-Experts (MoE) layer class names (case-sensitive) to wrap ,e.g, `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ...
167 `deepspeed_hostfile`: DeepSpeed hostfile for configuring multi-node compute resources.
168 `deepspeed_exclusion_filter`: DeepSpeed exclusion filter string when using mutli-node setup.
169 `deepspeed_inclusion_filter`: DeepSpeed inclusion filter string when using mutli-node setup.
170 `deepspeed_multinode_launcher`: DeepSpeed multi-node launcher to use, e.g. `pdsh`, `standard`, `openmpi`, `mvapich`, `mpich`, `slurm`, `nossh` (requires DeepSpeed >= 0.14.5). If unspecified, will default to `pdsh`.
171 `deepspeed_config_file`: path to the DeepSpeed config file in `json` format. See the next section for more details on this.
172 ```
173 To be able to tweak more options, you will need to use a DeepSpeed config file.
174
175 ### DeepSpeed Config File
176 On your machine(s) just run:
177
178 ```bash
179 accelerate config
180 ```
181
182 and answer the questions asked. It will ask whether you want to use a config file for deepspeed to which you answer yes
183 and provide the path to the deepspeed config file.
184 This will generate a config file that will be used automatically to properly set the
185 default options when doing
186
187 ```bash
188 accelerate launch my_script.py --args_to_my_script
189 ```
190
191 For instance, here is how you would run the NLP example `examples/by_feature/deepspeed_with_config_support.py` (from the root of the repo) with DeepSpeed Config File:
192
193 **ZeRO Stage-2 DeepSpeed Config File Example**
194 ```bash
195 compute_environment: LOCAL_MACHINE
196 deepspeed_config:
197 deepspeed_config_file: /home/ubuntu/accelerate/examples/deepspeed_config_templates/zero_stage2_config.json
198 zero3_init_flag: true
199 distributed_type: DEEPSPEED
200 fsdp_config: {}
201 machine_rank: 0
202 main_process_ip: null
203 main_process_port: null
204 main_training_function: main
205 mixed_precision: fp16
206 num_machines: 1
207 num_processes: 2
208 use_cpu: false
209 ```
210
211 with the contents of `zero_stage2_config.json` being:
212 ```json
213 {
214 "fp16": {
215 "enabled": true,
216 "loss_scale": 0,
217 "loss_scale_window": 1000,
218 "initial_scale_power": 16,
219 "hysteresis": 2,
220 "min_loss_scale": 1
221 },
222 "optimizer": {
223 "type": "AdamW",
224 "params": {
225 "lr": "auto",
226 "weight_decay": "auto",
227 "torch_adam": true,
228 "adam_w_mode": true
229 }
230 },
231 "scheduler": {
232 "type": "WarmupDecayLR",
233 "params": {
234 "warmup_min_lr": "auto",
235 "warmup_max_lr": "auto",
236 "warmup_num_steps": "auto",
237 "total_num_steps": "auto"
238 }
239 },
240 "zero_optimization": {
241 "stage": 2,
242 "allgather_partitions": true,
243 "allgather_bucket_size": 2e8,
244 "overlap_comm": true,
245 "reduce_scatter": true,
246 "reduce_bucket_size": "auto",
247 "contiguous_gradients": true
248 },
249 "gradient_accumulation_steps": 1,
250 "gradient_clipping": "auto",
251 "steps_per_print": 2000,
252 "train_batch_size": "auto",
253 "train_micro_batch_size_per_gpu": "auto",
254 "wall_clock_breakdown": false
255 }
256 ```
257
258 ```bash
259 accelerate launch examples/by_feature/deepspeed_with_config_support.py \
260 --config_name "gpt2-large" \
261 --tokenizer_name "gpt2-large" \
262 --dataset_name "wikitext" \
263 --dataset_config_name "wikitext-2-raw-v1" \
264 --block_size 128 \
265 --output_dir "./clm/clm_deepspeed_stage2_accelerate" \
266 --learning_rate 5e-4 \
267 --per_device_train_batch_size 24 \
268 --per_device_eval_batch_size 24 \
269 --num_train_epochs 3 \
270 --with_tracking \
271 --report_to "wandb"\
272 ```
273
274 **ZeRO Stage-3 with CPU offload DeepSpeed Config File Example**
275 ```bash
276 compute_environment: LOCAL_MACHINE
277 deepspeed_config:
278 deepspeed_config_file: /home/ubuntu/accelerate/examples/deepspeed_config_templates/zero_stage3_offload_config.json
279 zero3_init_flag: true
280 distributed_type: DEEPSPEED
281 fsdp_config: {}
282 machine_rank: 0
283 main_process_ip: null
284 main_process_port: null
285 main_training_function: main
286 mixed_precision: fp16
287 num_machines: 1
288 num_processes: 2
289 use_cpu: false
290 ```
291 with the contents of `zero_stage3_offload_config.json` being:
292 ```json
293 {
294 "fp16": {
295 "enabled": true,
296 "loss_scale": 0,
297 "loss_scale_window": 1000,
298 "initial_scale_power": 16,
299 "hysteresis": 2,
300 "min_loss_scale": 1
301 },
302 "optimizer": {
303 "type": "AdamW",
304 "params": {
305 "lr": "auto",
306 "weight_decay": "auto"
307 }
308 },
309 "scheduler": {
310 "type": "WarmupDecayLR",
311 "params": {
312 "warmup_min_lr": "auto",
313 "warmup_max_lr": "auto",
314 "warmup_num_steps": "auto",
315 "total_num_steps": "auto"
316 }
317 },
318 "zero_optimization": {
319 "stage": 3,
320 "offload_optimizer": {
321 "device": "cpu",
322 "pin_memory": true
323 },
324 "offload_param": {
325 "device": "cpu",
326 "pin_memory": true
327 },
328 "overlap_comm": true,
329 "contiguous_gradients": true,
330 "reduce_bucket_size": "auto",
331 "stage3_prefetch_bucket_size": "auto",
332 "stage3_param_persistence_threshold": "auto",
333 "sub_group_size": 1e9,
334 "stage3_max_live_parameters": 1e9,
335 "stage3_max_reuse_distance": 1e9,
336 "stage3_gather_16bit_weights_on_model_save": "auto"
337 },
338 "gradient_accumulation_steps": 1,
339 "gradient_clipping": "auto",
340 "steps_per_print": 2000,
341 "train_batch_size": "auto",
342 "train_micro_batch_size_per_gpu": "auto",
343 "wall_clock_breakdown": false
344 }
345 ```
346
347 ```bash
348 accelerate launch examples/by_feature/deepspeed_with_config_support.py \
349 --config_name "gpt2-large" \
350 --tokenizer_name "gpt2-large" \
351 --dataset_name "wikitext" \
352 --dataset_config_name "wikitext-2-raw-v1" \
353 --block_size 128 \
354 --output_dir "./clm/clm_deepspeed_stage3_offload_accelerate" \
355 --learning_rate 5e-4 \
356 --per_device_train_batch_size 32 \
357 --per_device_eval_batch_size 32 \
358 --num_train_epochs 3 \
359 --with_tracking \
360 --report_to "wandb"\
361 ```
362
363 **ZeRO++ Config Example**
364 You can use the features of ZeRO++ by using the appropriate config parameters. Note that ZeRO++ is an extension for ZeRO Stage 3. Here is how the config file can be modified, from [DeepSpeed's ZeRO++ tutorial](https://www.deepspeed.ai/tutorials/zeropp/):
365
366 ```json
367 {
368 "zero_optimization": {
369 "stage": 3,
370 "reduce_bucket_size": "auto",
371
372 "zero_quantized_weights": true,
373 "zero_hpz_partition_size": 8,
374 "zero_quantized_gradients": true,
375
376 "contiguous_gradients": true,
377 "overlap_comm": true
378 }
379 }
380 ```
381
382 For hierarchical partitioning, the partition size `zero_hpz_partition_size` should ideally be set to the number of GPUs per node. (For example, the above config file assumes 8 GPUs per node)
383
384 **Important code changes when using DeepSpeed Config File**
385
386 1. DeepSpeed Optimizers and Schedulers. For more information on these,
387 see the [DeepSpeed Optimizers](https://deepspeed.readthedocs.io/en/latest/optimizers.html) and [DeepSpeed Schedulers](https://deepspeed.readthedocs.io/en/latest/schedulers.html) documentation.
388 We will look at the changes needed in the code when using these.
389
390 a. DS Optim + DS Scheduler: The case when both `optimizer` and `scheduler` keys are present in the DeepSpeed config file.
391 In this situation, those will be used and the user has to use `accelerate.utils.DummyOptim` and `accelerate.utils.DummyScheduler` to replace the PyTorch/Custom optimizers and schedulers in their code.
392 Below is the snippet from `examples/by_feature/deepspeed_with_config_support.py` showing this:
393 ```python
394 # Creates Dummy Optimizer if `optimizer` was specified in the config file else creates Adam Optimizer
395 optimizer_cls = (
396 torch.optim.AdamW
397 if accelerator.state.deepspeed_plugin is None
398 or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config
399 else DummyOptim
400 )
401 optimizer = optimizer_cls(optimizer_grouped_parameters, lr=args.learning_rate)
402
403 # Creates Dummy Scheduler if `scheduler` was specified in the config file else creates `args.lr_scheduler_type` Scheduler
404 if (
405 accelerator.state.deepspeed_plugin is None
406 or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
407 ):
408 lr_scheduler = get_scheduler(
409 name=args.lr_scheduler_type,
410 optimizer=optimizer,
411 num_warmup_steps=args.num_warmup_steps,
412 num_training_steps=args.max_train_steps,
413 )
414 else:
415 lr_scheduler = DummyScheduler(
416 optimizer, total_num_steps=args.max_train_steps, warmup_num_steps=args.num_warmup_steps
417 )
418 ```
419 b. Custom Optim + Custom Scheduler: The case when both `optimizer` and `scheduler` keys are absent in the DeepSpeed config file.
420 In this situation, no code changes are needed from the user and this is the case when using integration via DeepSpeed Plugin.
421 In the above example we can see that the code remains unchanged if the `optimizer` and `scheduler` keys are absent in the DeepSpeed config file.
422
423 c. Custom Optim + DS Scheduler: The case when only `scheduler` key is present in the DeepSpeed config file.
424 In this situation, the user has to use `accelerate.utils.DummyScheduler` to replace the PyTorch/Custom scheduler in their code.
425
426 d. DS Optim + Custom Scheduler: The case when only `optimizer` key is present in the DeepSpeed config file.
427 This will result in an error because you can only use DS Scheduler when using DS Optim.
428
429 2. Notice the `auto` values in the above example DeepSpeed config files. These are automatically handled by `prepare` method
430 based on model, dataloaders, dummy optimizer and dummy schedulers provided to `prepare` method.
431 Only the `auto` fields specified in above examples are handled by `prepare` method and the rest have to be explicitly specified by the user.
432
433 The `auto` values are calculated as:
434
435 - `reduce_bucket_size`: `hidden_size * hidden_size`
436 - `stage3_prefetch_bucket_size`: `int(0.9 * hidden_size * hidden_size)`
437 - `stage3_param_persistence_threshold`: `10 * hidden_size`
438
439 For the `auto` feature to work for these 3 config entries - Accelerate will use `model.config.hidden_size` or `max(model.config.hidden_sizes)` as `hidden_size`. If neither of these is available, the launching will fail and you will have to set these 3 config entries manually. Remember the first 2 config entries are the communication buffers - the larger they are the more efficient the comms will be, and the larger they are the more GPU memory they will consume, so it's a tunable performance trade-off.
440
441
442 **Things to note when using DeepSpeed Config File**
443
444 Below is a sample script using `deepspeed_config_file` in different scenarios.
445
446 Code `test.py`:
447
448 ```python
449 from accelerate import Accelerator
450 from accelerate.state import AcceleratorState
451
452
453 def main():
454 accelerator = Accelerator()
455 accelerator.print(f"{AcceleratorState()}")
456
457
458 if __name__ == "__main__":
459 main()
460 ```
461
462 **Scenario 1**: Manually tampered accelerate config file having `deepspeed_config_file` along with other entries.
463
464 1. Content of the `accelerate` config:
465
466 ```yaml
467 command_file: null
468 commands: null
469 compute_environment: LOCAL_MACHINE
470 deepspeed_config:
471 gradient_accumulation_steps: 1
472 gradient_clipping: 1.0
473 offload_optimizer_device: 'cpu'
474 offload_param_device: 'cpu'
475 zero3_init_flag: true
476 zero3_save_16bit_model: true
477 zero_stage: 3
478 deepspeed_config_file: 'ds_config.json'
479 distributed_type: DEEPSPEED
480 downcast_bf16: 'no'
481 dynamo_backend: 'NO'
482 fsdp_config: {}
483 gpu_ids: null
484 machine_rank: 0
485 main_process_ip: null
486 main_process_port: null
487 main_training_function: main
488 megatron_lm_config: {}
489 num_machines: 1
490 num_processes: 2
491 rdzv_backend: static
492 same_network: true
493 tpu_name: null
494 tpu_zone: null
495 use_cpu: false
496 ```
497
498 2. `ds_config.json`:
499
500 ```json
501 {
502 "bf16": {
503 "enabled": true
504 },
505 "zero_optimization": {
506 "stage": 3,
507 "stage3_gather_16bit_weights_on_model_save": false,
508 "offload_optimizer": {
509 "device": "none"
510 },
511 "offload_param": {
512 "device": "none"
513 }
514 },
515 "gradient_clipping": 1.0,
516 "train_batch_size": "auto",
517 "train_micro_batch_size_per_gpu": "auto",
518 "gradient_accumulation_steps": 10,
519 "steps_per_print": 2000000
520 }
521 ```
522
523 3. Output of `accelerate launch test.py`:
524
525 ```bash
526 ValueError: When using `deepspeed_config_file`, the following accelerate config variables will be ignored:
527 ['gradient_accumulation_steps', 'gradient_clipping', 'zero_stage', 'offload_optimizer_device', 'offload_param_device',
528 'zero3_save_16bit_model', 'mixed_precision'].
529 Please specify them appropriately in the DeepSpeed config file.
530 If you are using an accelerate config file, remove other config variables mentioned in the above specified list.
531 The easiest method is to create a new config following the questionnaire via `accelerate config`.
532 It will only ask for the necessary config variables when using `deepspeed_config_file`.
533 ```
534
535 **Scenario 2**: Use the solution of the error to create new accelerate config and check that no ambiguity error is now thrown.
536
537 1. Run `accelerate config`:
538
539 ```bash
540 $ accelerate config
541 -------------------------------------------------------------------------------------------------------------------------------
542 In which compute environment are you running?
543 This machine
544 -------------------------------------------------------------------------------------------------------------------------------
545 Which type of machine are you using?
546 multi-GPU
547 How many different machines will you use (use more than 1 for multi-node training)? [1]:
548 Do you wish to optimize your script with torch dynamo?[yes/NO]:
549 Do you want to use DeepSpeed? [yes/NO]: yes
550 Do you want to specify a json file to a DeepSpeed config? [yes/NO]: yes
551 Please enter the path to the json DeepSpeed config file: ds_config.json
552 Do you want to enable `deepspeed.zero.Init` when using ZeRO Stage-3 for constructing massive models? [yes/NO]: yes
553 How many GPU(s) should be used for distributed training? [1]:4
554 accelerate configuration saved at ds_config_sample.yaml
555 ```
556
557 2. Content of the `accelerate` config:
558
559 ```yaml
560 compute_environment: LOCAL_MACHINE
561 deepspeed_config:
562 deepspeed_config_file: ds_config.json
563 zero3_init_flag: true
564 distributed_type: DEEPSPEED
565 downcast_bf16: 'no'
566 dynamo_backend: 'NO'
567 fsdp_config: {}
568 machine_rank: 0
569 main_training_function: main
570 megatron_lm_config: {}
571 num_machines: 1
572 num_processes: 4
573 rdzv_backend: static
574 same_network: true
575 use_cpu: false
576 ```
577
578 3. Output of `accelerate launch test.py`:
579
580 ```bash
581 Distributed environment: DEEPSPEED Backend: nccl
582 Num processes: 4
583 Process index: 0
584 Local process index: 0
585 Device: cuda:0
586 Mixed precision type: bf16
587 ds_config: {'bf16': {'enabled': True}, 'zero_optimization': {'stage': 3, 'stage3_gather_16bit_weights_on_model_save': False, 'offload_optimizer': {'device': 'none'}, 'offload_param': {'device': 'none'}}, 'gradient_clipping': 1.0, 'train_batch_size': 'auto', 'train_micro_batch_size_per_gpu': 'auto', 'gradient_accumulation_steps': 10, 'steps_per_print': inf, 'fp16': {'enabled': False}}
588 ```
589
590 **Scenario 3**: Setting the `accelerate launch` command arguments related to DeepSpeed as `"auto"` in the DeepSpeed` configuration file and check that things work as expected.
591
592 1. New `ds_config.json` with `"auto"` for the `accelerate launch` DeepSpeed command arguments:
593
594 ```json
595 {
596 "bf16": {
597 "enabled": "auto"
598 },
599 "zero_optimization": {
600 "stage": "auto",
601 "stage3_gather_16bit_weights_on_model_save": "auto",
602 "offload_optimizer": {
603 "device": "auto"
604 },
605 "offload_param": {
606 "device": "auto"
607 }
608 },
609 "gradient_clipping": "auto",
610 "train_batch_size": "auto",
611 "train_micro_batch_size_per_gpu": "auto",
612 "gradient_accumulation_steps": "auto",
613 "steps_per_print": 2000000
614 }
615 ```
616
617 2. Output of `accelerate launch --mixed_precision="fp16" --zero_stage=3 --gradient_accumulation_steps=5 --gradient_clipping=1.0 --offload_param_device="cpu" --offload_optimizer_device="nvme" --zero3_save_16bit_model="true" test.py`:
618
619 ```bash
620 Distributed environment: DEEPSPEED Backend: nccl
621 Num processes: 4
622 Process index: 0
623 Local process index: 0
624 Device: cuda:0
625 Mixed precision type: fp16
626 ds_config: {'bf16': {'enabled': False}, 'zero_optimization': {'stage': 3, 'stage3_gather_16bit_weights_on_model_save': True, 'offload_optimizer': {'device': 'nvme'}, 'offload_param': {'device': 'cpu'}}, 'gradient_clipping': 1.0, 'train_batch_size': 'auto', 'train_micro_batch_size_per_gpu': 'auto', 'gradient_accumulation_steps': 5, 'steps_per_print': inf, 'fp16': {'enabled': True, 'auto_cast': True}}
627 ```
628
629 **Note**:
630 1. Remaining `"auto"` values are handled in `accelerator.prepare()` call as explained in point 2 of
631 `Important code changes when using DeepSpeed Config File`.
632 2. Only when `gradient_accumulation_steps` is `auto`, the value passed while creating `Accelerator` object via `Accelerator(gradient_accumulation_steps=k)` will be used. When using DeepSpeed Plugin, the value from it will be used and it will overwrite the value passed while creating Accelerator object.
633
634 ## Saving and loading
635
636 1. Saving and loading of models is unchanged for ZeRO Stage-1 and Stage-2.
637
638 2. under ZeRO Stage-3, `state_dict` contains just the placeholders since the model weights are partitioned across multiple GPUs.
639 ZeRO Stage-3 has 2 options:
640
641 a. Saving the entire 16bit model weights to directly load later on using `model.load_state_dict(torch.load(pytorch_model.bin))`.
642 For this, either set `zero_optimization.stage3_gather_16bit_weights_on_model_save` to True in DeepSpeed Config file or set
643 `zero3_save_16bit_model` to True in DeepSpeed Plugin.
644 **Note that this option requires consolidation of the weights on one GPU it can be slow and memory demanding, so only use this feature when needed.**
645 Below is the snippet from `examples/by_feature/deepspeed_with_config_support.py` showing this:
646 ```python
647 unwrapped_model = accelerator.unwrap_model(model)
648
649 # New Code #
650 # Saves the whole/unpartitioned fp16 model when in ZeRO Stage-3 to the output directory if
651 # `stage3_gather_16bit_weights_on_model_save` is True in DeepSpeed Config file or
652 # `zero3_save_16bit_model` is True in DeepSpeed Plugin.
653 # For Zero Stages 1 and 2, models are saved as usual in the output directory.
654 # The model name saved is `pytorch_model.bin`
655 unwrapped_model.save_pretrained(
656 args.output_dir,
657 is_main_process=accelerator.is_main_process,
658 save_function=accelerator.save,
659 state_dict=accelerator.get_state_dict(model),
660 )
661 ```
662
663 b. To get 32bit weights, first save the model using `model.save_checkpoint()`.
664 Below is the snippet from `examples/by_feature/deepspeed_with_config_support.py` showing this:
665 ```python
666 success = model.save_checkpoint(PATH, ckpt_id, checkpoint_state_dict)
667 status_msg = f"checkpointing: PATH={PATH}, ckpt_id={ckpt_id}"
668 if success:
669 logging.info(f"Success {status_msg}")
670 else:
671 logging.warning(f"Failure {status_msg}")
672 ```
673 This will create ZeRO model and optimizer partitions along with `zero_to_fp32.py` script in checkpoint directory.
674 You can use this script to do offline consolidation.
675 It requires no configuration files or GPUs. Here is an example of its usage:
676 ```bash
677 $ cd /path/to/checkpoint_dir
678 $ ./zero_to_fp32.py . pytorch_model.bin
679 Processing zero checkpoint at global_step1
680 Detected checkpoint of type zero stage 3, world_size: 2
681 Saving fp32 state dict to pytorch_model.bin (total_numel=60506624)
682 ```
683 To get 32bit model for saving/inference, you can perform:
684 ```python
685 from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
686
687 unwrapped_model = accelerator.unwrap_model(model)
688 fp32_model = load_state_dict_from_zero_checkpoint(unwrapped_model, checkpoint_dir)
689 ```
690 If you are only interested in the `state_dict`, you can do the following:
691 ```python
692 from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
693
694 state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir)
695 ```
696 Note that all these functions require ~2x memory (general RAM) of the size of the final checkpoint.
697
698 ## ZeRO Inference
699 DeepSpeed ZeRO Inference supports ZeRO stage 3 with ZeRO-Infinity.
700 It uses the same ZeRO protocol as training, but it doesn't use an optimizer and a lr scheduler and only stage 3 is relevant.
701 With accelerate integration, you just need to prepare the model and dataloader as shown below:
702
703 ```python
704 model, eval_dataloader = accelerator.prepare(model, eval_dataloader)
705 ```
706
707 ## Few caveats to be aware of
708
709 1. Current integration doesn’t support Pipeline Parallelism of DeepSpeed.
710 2. Current integration doesn’t support `mpu`, limiting the tensor parallelism which is supported in Megatron-LM.
711 3. Current integration doesn’t support multiple models.
712
713 ## Multi-node DeepSpeed
714 DeepSpeed supports multi-node inference and training over a variety of different launchers. You can specify a different launcher by setting the `deepspeed_multinode_launcher` config in the CLI or in the DeepSpeed config file.
715
716 Currently, accelerate supports passing configuration for the following DeepSpeed multi-node launchers: `pdsh` (default), `standard`, `openmpi`, `mvapich`, `mpich`, `slurm`, `nossh` (requires DeepSpeed >= 0.14.5).
717
718 Please read the [DeepSpeed documentation](https://www.deepspeed.ai/getting-started/#resource-configuration-multi-node) for more information on the different launchers. By default, DeepSpeed will attempt to use passwordless SSH from the main machine node to the other nodes to perform the launcher command. In this configuration, the accelerate launch command only needs to be run on the main node. If using the `nossh` launcher, you will need to run the accelerate launch command on every node using copied configuration.
719
720 ## DeepSpeed Resources
721
722 The documentation for the internals related to deepspeed can be found [here](../package_reference/deepspeed).
723
724 - [Project's github](https://github.com/deepspeedai/DeepSpeed)
725 - [Usage docs](https://www.deepspeed.ai/getting-started/)
726 - [API docs](https://deepspeed.readthedocs.io/en/latest/index.html)
727 - [Blog posts](https://www.microsoft.com/en-us/research/search/?q=deepspeed)
728
729 Papers:
730
731 - [ZeRO: Memory Optimizations Toward Training Trillion Parameter Models](https://huggingface.co/papers/1910.02054)
732 - [ZeRO-Offload: Democratizing Billion-Scale Model Training](https://huggingface.co/papers/2101.06840)
733 - [ZeRO-Infinity: Breaking the GPU Memory Wall for Extreme Scale Deep Learning](https://huggingface.co/papers/2104.07857)
734 - [ZeRO++: Extremely Efficient Collective Communication for Giant Model Training](https://huggingface.co/papers/2306.10209)
735
736
737 Finally, please, remember that `Accelerate` only integrates DeepSpeed, therefore if you
738 have any problems or questions with regards to DeepSpeed usage, please, file an issue with [DeepSpeed GitHub](https://github.com/deepspeedai/DeepSpeed/issues).
739
740
741 <Tip>
742
743 For those interested in the similarities and differences between FSDP and DeepSpeed, please check out the [concept guide here](../concept_guides/fsdp_and_deepspeed)!
744
745 </Tip>