diff --git a/docs/source/en/_toctree.yml b/docs/source/en/_toctree.yml index 57d257362ba62b..5116e4219fbcb1 100644 --- a/docs/source/en/_toctree.yml +++ b/docs/source/en/_toctree.yml @@ -111,6 +111,8 @@ title: Share a custom model - local: chat_templating title: Templates for chat models + - local: trainer + title: Trainer - local: sagemaker title: Run training on Amazon SageMaker - local: serialization @@ -135,13 +137,13 @@ title: Overview - local: quantization title: Quantization - - local: trainer - title: Trainer - sections: - local: perf_train_gpu_one title: Methods and tools for efficient training on a single GPU - local: perf_train_gpu_many title: Multiple GPUs and parallelism + - local: fsdp + title: Fully Sharded Data Parallel - local: perf_train_cpu title: Efficient training on CPU - local: perf_train_cpu_many @@ -164,7 +166,7 @@ - local: big_models title: Instantiating a big model - local: debugging - title: Troubleshooting + title: Debugging - local: tf_xla title: XLA Integration for TensorFlow Models - local: perf_torch_compile diff --git a/docs/source/en/debugging.md b/docs/source/en/debugging.md index b1a430e7344e96..9c5c0753ab4d41 100644 --- a/docs/source/en/debugging.md +++ b/docs/source/en/debugging.md @@ -16,6 +16,74 @@ rendered properly in your Markdown viewer. # Debugging +Training on multiple GPUs can be a tricky endeavor whether you're running into installation issues or communication problems between your GPUs. This debugging guide covers some issues you may run into and how to resolve them. + +## DeepSpeed CUDA installation + +If you're using DeepSpeed, you've probably already installed it with the following command. + +```bash +pip install deepspeed +``` + +DeepSpeed compiles CUDA C++ code and it can be a potential source of errors when building PyTorch extensions that require CUDA. These errors depend on how CUDA is installed on your system, and this section focuses on PyTorch built with *CUDA 10.2*. + + + +For any other installation issues, please [open an issue](https://github.com/microsoft/DeepSpeed/issues) with the DeepSpeed team. + + + +### Non-identical CUDA toolkits + +PyTorch comes with its own CUDA toolkit, but to use DeepSpeed with PyTorch, you need to have an identical version of CUDA installed system-wide. For example, if you installed PyTorch with `cudatoolkit==10.2` in your Python environment, then you'll also need to have CUDA 10.2 installed system-wide. If you don't have CUDA installed system-wide, you should install it first. + +The exact location may vary from system to system, but `usr/local/cuda-10.2` is the most common location on many Unix systems. When CUDA is correctly setup and added to your `PATH` environment variable, you can find the installation location with the following command: + +```bash +which nvcc +``` + +### Multiple CUDA toolkits + +You may also have more than one CUDA toolkit installed system-wide. + +```bash +/usr/local/cuda-10.2 +/usr/local/cuda-11.0 +``` + +Typically, package installers set the paths to whatever the last version was installed. If the package build fails because it can't find the right CUDA version (despite it being installed system-wide already), then you need to configure the `PATH` and `LD_LIBRARY_PATH` environment variables to point to the correct path. + +Take a look at the contents of these environment variables first: + +```bash +echo $PATH +echo $LD_LIBRARY_PATH +``` + +`PATH` lists the locations of the executables and `LD_LIBRARY_PATH` lists where to look for shared libraries. Earlier entries are prioritized over later ones, and `:` is used to separate multiple entries. To tell the build program where to find the specific CUDA toolkit you want, insert the correct path to list first. This command prepends rather than overwrites the existing values. + +```bash +# adjust the version and full path if needed +export PATH=/usr/local/cuda-10.2/bin:$PATH +export LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATH +``` + +In addition, you should also check the directories you assign actually exist. The `lib64` sub-directory contains various CUDA `.so` objects (like `libcudart.so`) and while it is unlikely your system names them differently, you should check the actual names and change them accordingly. + +### Older CUDA versions + +Sometimes, older CUDA versions may refuse to build with newer compilers. For example, if you have `gcc-9` but CUDA wants `gcc-7`. Usually, installing the latest CUDA toolkit enables support for the newer compiler. + +You could also install an older version of the compiler in addition to the one you're currently using (or it may already be installed but it's not used by default and the build system can't see it). To resolve this, you can create a symlink to give the build system visibility to the older compiler. + +```bash +# adapt the path to your system +sudo ln -s /usr/bin/gcc-7 /usr/local/cuda-10.2/bin/gcc +sudo ln -s /usr/bin/g++-7 /usr/local/cuda-10.2/bin/g++ +``` + ## Multi-GPU Network Issues Debug When training or inferencing with `DistributedDataParallel` and multiple GPU, if you run into issue of inter-communication between processes and/or nodes, you can use the following script to diagnose network issues. diff --git a/docs/source/en/fsdp.md b/docs/source/en/fsdp.md new file mode 100644 index 00000000000000..6b90ab5ad6d6d5 --- /dev/null +++ b/docs/source/en/fsdp.md @@ -0,0 +1,138 @@ + + +# Fully Sharded Data Parallel + +[Fully Sharded Data Parallel (FSDP)](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) is a data parallel method that shards a model's parameters, gradients and optimizer states across the number of available GPUs (also called workers or *rank*). Unlike [DistributedDataParallel (DDP)](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html), FSDP reduces memory-usage because a model is replicated on each GPU. This improves GPU memory-efficiency and allows you to train much larger models on fewer GPUs. FSDP is integrated with the Accelerate, a library for easily managing training in distributed environments, which means it is available for use from the [`Trainer`] class. + +Before you start, make sure Accelerate is installed and at least PyTorch 2.1.0 or newer. + +```bash +pip install accelerate +``` + +## FSDP configuration + +To start, run the [`accelerate config`](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-config) command to create a configuration file for your training environment. Accelerate uses this configuration file to automatically setup the correct training environment based on your selected training options in `accelerate config`. + +```bash +accelerate config +``` + +When you run `accelerate config`, you'll be prompted with a series of options to configure your training environment. This section covers some of the most important FSDP options. To learn more about the other available FSDP options, take a look at the [fsdp_config](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.fsdp_config) parameters. + +### Sharding strategy + +FSDP offers a number of sharding strategies to select from: + +* `FULL_SHARD` - shards model parameters, gradients and optimizer states across workers; select `1` for this option +* `SHARD_GRAD_OP`- shard gradients and optimizer states across workers; select `2` for this option +* `NO_SHARD` - don't shard anything (this is equivalent to DDP); select `3` for this option +* `HYBRID_SHARD` - shard model parameters, gradients and optimizer states within each worker where each worker also has a full copy; select `4` for this option +* `HYBRID_SHARD_ZERO2` - shard gradients and optimizer states within each worker where each worker also has a full copy; select `5` for this option + +This is enabled by the `fsdp_sharding_strategy` flag. + +### CPU offload + +You could also offload parameters and gradients when they are not in use to the CPU to save even more GPU memory and help you fit large models where even FSDP may not be sufficient. This is enabled by setting `fsdp_offload_params: true` when running `accelerate config`. + +### Wrapping policy + +FSDP is applied by wrapping each layer in the network. The wrapping is usually applied in a nested way where the full weights are discarded after each forward pass to save memory for use in the next layer. The *auto wrapping* policy is the simplest way to implement this and you don't need to change any code. You should select `fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP` to wrap a Transformer layer and `fsdp_transformer_layer_cls_to_wrap` to specify which layer to wrap (for example `BertLayer`). + +Otherwise, you can choose a size-based wrapping policy where FSDP is applied to a layer if it exceeds a certain number of parameters. This is enabled by setting `fsdp_wrap_policy: SIZE_BASED_WRAP` and `min_num_param` to the desired size threshold. + +### Checkpointing + +Intermediate checkpoints should be saved with `fsdp_state_dict_type: SHARDED_STATE_DICT` because saving the full state dict with CPU offloading on rank 0 takes a lot of time and often results in `NCCL Timeout` errors due to indefinite hanging during broadcasting. You can resume training with the sharded state dicts with the [`~accelerate.Accelerator.load_state`]` method. + +```py +# directory containing checkpoints +accelerator.load_state("ckpt") +``` + +However, when training ends, you want to save the full state dict because sharded state dict is only compatible with FSDP. + +```py +if trainer.is_fsdp_enabled: + trainer.accelerator.state.fsdp_plugin.set_state_dict_type("FULL_STATE_DICT") + +trainer.save_model(script_args.output_dir) +``` + +### TPU + +[PyTorch XLA](https://pytorch.org/xla/release/2.1/index.html) supports FSDP training for TPUs and it can be enabled by modifying the FSDP configuration file generated by `accelerate config`. In addition to the sharding strategies and wrapping options specified above, you can add the parameters shown below to the file. + +```yaml +xla: True # must be set to True to enable PyTorch/XLA +xla_fsdp_settings: # XLA-specific FSDP parameters +xla_fsdp_grad_ckpt: True # use gradient checkpointing +``` + +The [`xla_fsdp_settings`](https://github.com/pytorch/xla/blob/2e6e183e0724818f137c8135b34ef273dea33318/torch_xla/distributed/fsdp/xla_fully_sharded_data_parallel.py#L128) allow you to configure additional XLA-specific parameters for FSDP. + +## Launch training + +An example FSDP configuration file may look like: + +```yaml +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: FSDP +downcast_bf16: 'no' +fsdp_config: + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_backward_prefetch_policy: BACKWARD_PRE + fsdp_cpu_ram_efficient_loading: true + fsdp_forward_prefetch: false + fsdp_offload_params: true + fsdp_sharding_strategy: 1 + fsdp_state_dict_type: SHARDED_STATE_DICT + fsdp_sync_module_states: true + fsdp_transformer_layer_cls_to_wrap: BertLayer + fsdp_use_orig_params: true +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 2 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false +``` + +To launch training, run the [`accelerate launch`](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-launch) command and it'll automatically use the configuration file you previously created with `accelerate config`. + +```bash +accelerate launch my-trainer-script.py +``` + +```bash +accelerate launch --fsdp="full shard" --fsdp_config="path/to/fsdp_config/ my-trainer-script.py +``` + +## Next steps + +FSDP can be a powerful tool for training really large models and you have access to more than one GPU or TPU. By sharding the model parameters, optimizer and gradient states, and even offloading them to the CPU when they're inactive, FSDP can reduce the high cost of large-scale training. If you're interested in learning more, the following may be helpful: + +* Follow along with the more in-depth Accelerate guide for [FSDP](https://huggingface.co/docs/accelerate/usage_guides/fsdp). +* Read the [Introducing PyTorch Fully Sharded Data Parallel (FSDP) API](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) blog post. +* Read the [Scaling PyTorch models on Cloud TPUs with FSDP](https://pytorch.org/blog/scaling-pytorch-models-on-cloud-tpus-with-fsdp/) blog post. diff --git a/docs/source/en/main_classes/trainer.md b/docs/source/en/main_classes/trainer.md index 2b2f5c3d5f8865..3f33ff1e505a2a 100644 --- a/docs/source/en/main_classes/trainer.md +++ b/docs/source/en/main_classes/trainer.md @@ -52,346 +52,3 @@ when used with other models. When using it with your own model, make sure: [[autodoc]] Seq2SeqTrainingArguments - all - -## Specific GPUs Selection - -Let's discuss how you can tell your program which GPUs are to be used and in what order. - -When using [`DistributedDataParallel`](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html) to use only a subset of your GPUs, you simply specify the number of GPUs to use. For example, if you have 4 GPUs, but you wish to use the first 2 you can do: - -```bash -torchrun --nproc_per_node=2 trainer-program.py ... -``` - -if you have either [`accelerate`](https://github.com/huggingface/accelerate) or [`deepspeed`](https://github.com/microsoft/DeepSpeed) installed you can also accomplish the same by using one of: - -```bash -accelerate launch --num_processes 2 trainer-program.py ... -``` - -```bash -deepspeed --num_gpus 2 trainer-program.py ... -``` - -You don't need to use the Accelerate or [the Deepspeed integration](deepspeed) features to use these launchers. - - -Until now you were able to tell the program how many GPUs to use. Now let's discuss how to select specific GPUs and control their order. - -The following environment variables help you control which GPUs to use and their order. - -**`CUDA_VISIBLE_DEVICES`** - -If you have multiple GPUs and you'd like to use only 1 or a few of those GPUs, set the environment variable `CUDA_VISIBLE_DEVICES` to a list of the GPUs to be used. - -For example, let's say you have 4 GPUs: 0, 1, 2 and 3. To run only on the physical GPUs 0 and 2, you can do: - -```bash -CUDA_VISIBLE_DEVICES=0,2 torchrun trainer-program.py ... -``` - -So now pytorch will see only 2 GPUs, where your physical GPUs 0 and 2 are mapped to `cuda:0` and `cuda:1` correspondingly. - -You can even change their order: - -```bash -CUDA_VISIBLE_DEVICES=2,0 torchrun trainer-program.py ... -``` - -Here your physical GPUs 0 and 2 are mapped to `cuda:1` and `cuda:0` correspondingly. - -The above examples were all for `DistributedDataParallel` use pattern, but the same method works for [`DataParallel`](https://pytorch.org/docs/stable/generated/torch.nn.DataParallel.html) as well: - -```bash -CUDA_VISIBLE_DEVICES=2,0 python trainer-program.py ... -``` - -To emulate an environment without GPUs simply set this environment variable to an empty value like so: - -```bash -CUDA_VISIBLE_DEVICES= python trainer-program.py ... -``` - -As with any environment variable you can, of course, export those instead of adding these to the command line, as in: - - -```bash -export CUDA_VISIBLE_DEVICES=0,2 -torchrun trainer-program.py ... -``` - -but this approach can be confusing since you may forget you set up the environment variable earlier and not understand why the wrong GPUs are used. Therefore, it's a common practice to set the environment variable just for a specific run on the same command line as it's shown in most examples of this section. - -**`CUDA_DEVICE_ORDER`** - -There is an additional environment variable `CUDA_DEVICE_ORDER` that controls how the physical devices are ordered. The two choices are: - -1. ordered by PCIe bus IDs (matches `nvidia-smi` and `rocm-smi`'s order) - this is the default. - -```bash -export CUDA_DEVICE_ORDER=PCI_BUS_ID -``` - -2. ordered by GPU compute capabilities - -```bash -export CUDA_DEVICE_ORDER=FASTEST_FIRST -``` - -Most of the time you don't need to care about this environment variable, but it's very helpful if you have a lopsided setup where you have an old and a new GPUs physically inserted in such a way so that the slow older card appears to be first. One way to fix that is to swap the cards. But if you can't swap the cards (e.g., if the cooling of the devices gets impacted) then setting `CUDA_DEVICE_ORDER=FASTEST_FIRST` will always put the newer faster card first. It'll be somewhat confusing though since `nvidia-smi` (or `rocm-smi`) will still report them in the PCIe order. - -The other solution to swapping the order is to use: - -```bash -export CUDA_VISIBLE_DEVICES=1,0 -``` -In this example we are working with just 2 GPUs, but of course the same would apply to as many GPUs as your computer has. - -Also if you do set this environment variable it's the best to set it in your `~/.bashrc` file or some other startup config file and forget about it. - -## Trainer Integrations - -The [`Trainer`] has been extended to support libraries that may dramatically improve your training -time and fit much bigger models. - -Currently it supports third party solutions, [DeepSpeed](https://github.com/microsoft/DeepSpeed) and [PyTorch FSDP](https://pytorch.org/docs/stable/fsdp.html), which implement parts of the paper [ZeRO: Memory Optimizations -Toward Training Trillion Parameter Models, by Samyam Rajbhandari, Jeff Rasley, Olatunji Ruwase, Yuxiong He](https://arxiv.org/abs/1910.02054). - -This provided support is new and experimental as of this writing. While the support for DeepSpeed and PyTorch FSDP is active and we welcome issues around it, we don't support the FairScale integration anymore since it has been integrated in PyTorch main (see the [PyTorch FSDP integration](#pytorch-fully-sharded-data-parallel)) - - - -### CUDA Extension Installation Notes - -As of this writing, Deepspeed require compilation of CUDA C++ code, before it can be used. - -While all installation issues should be dealt with through the corresponding GitHub Issues of [Deepspeed](https://github.com/microsoft/DeepSpeed/issues), there are a few common issues that one may encounter while building -any PyTorch extension that needs to build CUDA extensions. - -Therefore, if you encounter a CUDA-related build issue while doing the following: - -```bash -pip install deepspeed -``` - -please, read the following notes first. - -In these notes we give examples for what to do when `pytorch` has been built with CUDA `10.2`. If your situation is -different remember to adjust the version number to the one you are after. - -#### Possible problem #1 - -While, Pytorch comes with its own CUDA toolkit, to build these two projects you must have an identical version of CUDA -installed system-wide. - -For example, if you installed `pytorch` with `cudatoolkit==10.2` in the Python environment, you also need to have -CUDA `10.2` installed system-wide. - -The exact location may vary from system to system, but `/usr/local/cuda-10.2` is the most common location on many -Unix systems. When CUDA is correctly set up and added to the `PATH` environment variable, one can find the -installation location by doing: - -```bash -which nvcc -``` - -If you don't have CUDA installed system-wide, install it first. You will find the instructions by using your favorite -search engine. For example, if you're on Ubuntu you may want to search for: [ubuntu cuda 10.2 install](https://www.google.com/search?q=ubuntu+cuda+10.2+install). - -#### Possible problem #2 - -Another possible common problem is that you may have more than one CUDA toolkit installed system-wide. For example you -may have: - -```bash -/usr/local/cuda-10.2 -/usr/local/cuda-11.0 -``` - -Now, in this situation you need to make sure that your `PATH` and `LD_LIBRARY_PATH` environment variables contain -the correct paths to the desired CUDA version. Typically, package installers will set these to contain whatever the -last version was installed. If you encounter the problem, where the package build fails because it can't find the right -CUDA version despite you having it installed system-wide, it means that you need to adjust the 2 aforementioned -environment variables. - -First, you may look at their contents: - -```bash -echo $PATH -echo $LD_LIBRARY_PATH -``` - -so you get an idea of what is inside. - -It's possible that `LD_LIBRARY_PATH` is empty. - -`PATH` lists the locations of where executables can be found and `LD_LIBRARY_PATH` is for where shared libraries -are to looked for. In both cases, earlier entries have priority over the later ones. `:` is used to separate multiple -entries. - -Now, to tell the build program where to find the specific CUDA toolkit, insert the desired paths to be listed first by -doing: - -```bash -export PATH=/usr/local/cuda-10.2/bin:$PATH -export LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATH -``` - -Note that we aren't overwriting the existing values, but prepending instead. - -Of course, adjust the version number, the full path if need be. Check that the directories you assign actually do -exist. `lib64` sub-directory is where the various CUDA `.so` objects, like `libcudart.so` reside, it's unlikely -that your system will have it named differently, but if it is adjust it to reflect your reality. - - -#### Possible problem #3 - -Some older CUDA versions may refuse to build with newer compilers. For example, you my have `gcc-9` but it wants -`gcc-7`. - -There are various ways to go about it. - -If you can install the latest CUDA toolkit it typically should support the newer compiler. - -Alternatively, you could install the lower version of the compiler in addition to the one you already have, or you may -already have it but it's not the default one, so the build system can't see it. If you have `gcc-7` installed but the -build system complains it can't find it, the following might do the trick: - -```bash -sudo ln -s /usr/bin/gcc-7 /usr/local/cuda-10.2/bin/gcc -sudo ln -s /usr/bin/g++-7 /usr/local/cuda-10.2/bin/g++ -``` - -Here, we are making a symlink to `gcc-7` from `/usr/local/cuda-10.2/bin/gcc` and since -`/usr/local/cuda-10.2/bin/` should be in the `PATH` environment variable (see the previous problem's solution), it -should find `gcc-7` (and `g++7`) and then the build will succeed. - -As always make sure to edit the paths in the example to match your situation. - - -### PyTorch Fully Sharded Data parallel - -To accelerate training huge models on larger batch sizes, we can use a fully sharded data parallel model. -This type of data parallel paradigm enables fitting more data and larger models by sharding the optimizer states, gradients and parameters. -To read more about it and the benefits, check out the [Fully Sharded Data Parallel blog](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/). -We have integrated the latest PyTorch's Fully Sharded Data Parallel (FSDP) training feature. -All you need to do is enable it through the config. - -**Required PyTorch version for FSDP support**: PyTorch >=2.1.0 - -**Usage**: - -- Make sure you have added the distributed launcher -`-m torch.distributed.launch --nproc_per_node=NUMBER_OF_GPUS_YOU_HAVE` if you haven't been using it already. - -- **Sharding Strategy**: - - FULL_SHARD : Shards optimizer states + gradients + model parameters across data parallel workers/GPUs. - For this, add `--fsdp full_shard` to the command line arguments. - - SHARD_GRAD_OP : Shards optimizer states + gradients across data parallel workers/GPUs. - For this, add `--fsdp shard_grad_op` to the command line arguments. - - NO_SHARD : No sharding. For this, add `--fsdp no_shard` to the command line arguments. - - HYBRID_SHARD : No sharding. For this, add `--fsdp hybrid_shard` to the command line arguments. - - HYBRID_SHARD_ZERO2 : No sharding. For this, add `--fsdp hybrid_shard_zero2` to the command line arguments. -- To offload the parameters and gradients to the CPU, - add `--fsdp "full_shard offload"` or `--fsdp "shard_grad_op offload"` to the command line arguments. -- To automatically recursively wrap layers with FSDP using `default_auto_wrap_policy`, - add `--fsdp "full_shard auto_wrap"` or `--fsdp "shard_grad_op auto_wrap"` to the command line arguments. -- To enable both CPU offloading and auto wrapping, - add `--fsdp "full_shard offload auto_wrap"` or `--fsdp "shard_grad_op offload auto_wrap"` to the command line arguments. -- Remaining FSDP config is passed via `--fsdp_config `. It is either a location of - FSDP json config file (e.g., `fsdp_config.json`) or an already loaded json file as `dict`. - - If auto wrapping is enabled, you can either use transformer based auto wrap policy or size based auto wrap policy. - - For transformer based auto wrap policy, it is recommended to specify `transformer_layer_cls_to_wrap` in the config file. If not specified, the default value is `model._no_split_modules` when available. - This specifies the list of transformer layer class name (case-sensitive) to wrap ,e.g, [`BertLayer`], [`GPTJBlock`], [`T5Block`] .... - This is important because submodules that share weights (e.g., embedding layer) should not end up in different FSDP wrapped units. - Using this policy, wrapping happens for each block containing Multi-Head Attention followed by couple of MLP layers. - Remaining layers including the shared embeddings are conveniently wrapped in same outermost FSDP unit. - Therefore, use this for transformer based models. - - For size based auto wrap policy, please add `min_num_params` in the config file. - It specifies FSDP's minimum number of parameters for auto wrapping. - - `backward_prefetch` can be specified in the config file. It controls when to prefetch next set of parameters. - `backward_pre` and `backward_pos` are available options. - For more information refer `torch.distributed.fsdp.fully_sharded_data_parallel.BackwardPrefetch` - - `forward_prefetch` can be specified in the config file. It controls when to prefetch next set of parameters. - If `"True"`, FSDP explicitly prefetches the next upcoming all-gather while executing in the forward pass. - - `limit_all_gathers` can be specified in the config file. - If `"True"`, FSDP explicitly synchronizes the CPU thread to prevent too many in-flight all-gathers. - - `activation_checkpointing` can be specified in the config file. - If `"True"`, FSDP activation checkpointing is a technique to reduce memory usage by clearing activations of - certain layers and recomputing them during a backward pass. Effectively, this trades extra computation time - for reduced memory usage. - - `use_orig_params` can be specified in the config file. - If True, allows non-uniform `requires_grad` during init, which means support for interspersed frozen and trainable paramteres. Useful in cases such as parameter-efficient fine-tuning. This also enables to have different optimizer param groups. This should be `True` when creating optimizer object before preparing/wrapping the model with FSDP. - Please refer this [blog](https://dev-discuss.pytorch.org/t/rethinking-pytorch-fully-sharded-data-parallel-fsdp-from-first-principles/1019). - -**Saving and loading** -Saving entire intermediate checkpoints using `FULL_STATE_DICT` state_dict_type with CPU offloading on rank 0 takes a lot of time and often results in NCCL Timeout errors due to indefinite hanging during broadcasting. However, at the end of training, we want the whole model state dict instead of the sharded state dict which is only compatible with FSDP. Use `SHARDED_STATE_DICT` (default) state_dict_type to save the intermediate checkpoints and optimizer states in this format recommended by the PyTorch team. - -Saving the final checkpoint in transformers format using default `safetensors` format requires below changes. -```python -if trainer.is_fsdp_enabled: - trainer.accelerator.state.fsdp_plugin.set_state_dict_type("FULL_STATE_DICT") - -trainer.save_model(script_args.output_dir) -``` - -**Few caveats to be aware of** -- it is incompatible with `generate`, thus is incompatible with `--predict_with_generate` - in all seq2seq/clm scripts (translation/summarization/clm etc.). - Please refer issue [#21667](https://github.com/huggingface/transformers/issues/21667) - -### PyTorch/XLA Fully Sharded Data parallel - -For all the TPU users, great news! PyTorch/XLA now supports FSDP. -All the latest Fully Sharded Data Parallel (FSDP) training are supported. -For more information refer to the [Scaling PyTorch models on Cloud TPUs with FSDP](https://pytorch.org/blog/scaling-pytorch-models-on-cloud-tpus-with-fsdp/) and [PyTorch/XLA implementation of FSDP](https://github.com/pytorch/xla/tree/master/torch_xla/distributed/fsdp) -All you need to do is enable it through the config. - -**Required PyTorch/XLA version for FSDP support**: >=2.0 - -**Usage**: - -Pass `--fsdp "full shard"` along with following changes to be made in `--fsdp_config `: -- `xla` should be set to `True` to enable PyTorch/XLA FSDP. -- `xla_fsdp_settings` The value is a dictionary which stores the XLA FSDP wrapping parameters. - For a complete list of options, please see [here]( - https://github.com/pytorch/xla/blob/master/torch_xla/distributed/fsdp/xla_fully_sharded_data_parallel.py). -- `xla_fsdp_grad_ckpt`. When `True`, uses gradient checkpointing over each nested XLA FSDP wrapped layer. - This setting can only be used when the xla flag is set to true, and an auto wrapping policy is specified through - `min_num_params` or `transformer_layer_cls_to_wrap`. -- You can either use transformer based auto wrap policy or size based auto wrap policy. - - For transformer based auto wrap policy, it is recommended to specify `transformer_layer_cls_to_wrap` in the config file. If not specified, the default value is `model._no_split_modules` when available. - This specifies the list of transformer layer class name (case-sensitive) to wrap ,e.g, [`BertLayer`], [`GPTJBlock`], [`T5Block`] .... - This is important because submodules that share weights (e.g., embedding layer) should not end up in different FSDP wrapped units. - Using this policy, wrapping happens for each block containing Multi-Head Attention followed by couple of MLP layers. - Remaining layers including the shared embeddings are conveniently wrapped in same outermost FSDP unit. - Therefore, use this for transformer based models. - - For size based auto wrap policy, please add `min_num_params` in the config file. - It specifies FSDP's minimum number of parameters for auto wrapping. - -Sections that were moved: - -[ DeepSpeed -| Installation -| Deployment with multiple GPUs -| Deployment with one GPU -| Deployment in Notebooks -| Configuration -| Passing Configuration -| Shared Configuration -| ZeRO -| ZeRO-2 Config -| ZeRO-3 Config -| NVMe Support -| ZeRO-2 vs ZeRO-3 Performance -| ZeRO-2 Example -| ZeRO-3 Example -| Optimizer -| Scheduler -| fp32 Precision -| Automatic Mixed Precision -| Batch Size -| Gradient Accumulation -| Gradient Clipping -| Getting The Model Weights Out -] diff --git a/docs/source/en/perf_train_gpu_many.md b/docs/source/en/perf_train_gpu_many.md index 4d89cf341a555d..3045b98952de4d 100644 --- a/docs/source/en/perf_train_gpu_many.md +++ b/docs/source/en/perf_train_gpu_many.md @@ -577,3 +577,83 @@ for that. And then you can train. A different setup will have its own custom opt 🤗 Transformers status: Transformers models are FX-trace-able via [transformers.utils.fx](https://github.com/huggingface/transformers/blob/master/src/transformers/utils/fx.py), which is a prerequisite for FlexFlow, however, changes are required on the FlexFlow side to make it work with Transformers models. + +## GPU selection + +When training on multiple GPUs, you can specify the number of GPUs to use and in what order. This can be useful for instance when you have GPUs with different computing power and want to use the faster GPU first. The selection process works for both [DistributedDataParallel](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html) and [DataParallel](https://pytorch.org/docs/stable/generated/torch.nn.DataParallel.html) to use only a subset of the available GPUs, and you don't need Accelerate or the [DeepSpeed integration](./main_classes/deepspeed). + +### Number of GPUs + +For example, if you have 4 GPUs and you only want to use the first 2: + + + + +Use the `--nproc_per_node` to select how many GPUs to use. + +```bash +torchrun --nproc_per_node=2 trainer-program.py ... +``` + + + + +Use `--num_processes` to select how many GPUs to use. + +```bash +accelerate launch --num_processes 2 trainer-program.py ... +``` + + + + +Use `--num_gpus` to select how many GPUs to use. + +```bash +deepspeed --num_gpus 2 trainer-program.py ... +``` + + + + +### Order of GPUs + +Now, to select which GPUs to use and their order, you'll use the `CUDA_VISIBLE_DEVICES` environment variable. It is easiest to set the environment variable in a `~/bashrc` or another startup config file. `CUDA_VISIBLE_DEVICES` is used to map which GPUs are used. For example, if you have 4 GPUs (0, 1, 2, 3) and you only want to run GPUs 0 and 2: + +```bash +CUDA_VISIBLE_DEVICES=0,2 torchrun trainer-program.py ... +``` + +Only the 2 physical GPUs (0 and 2) are "visible" to PyTorch and these are mapped to `cuda:0` and `cuda:1` respectively. You can also reverse the order of the GPUs to use 2 first. Now, the mapping is `cuda:1` for GPU 0 and `cuda:0` for GPU 2. + +```bash +CUDA_VISIBLE_DEVICES=2,0 torchrun trainer-program.py ... +``` + +You can also set the `CUDA_VISIBLE_DEVICES` environment variable to an empty value to create an environment without GPUs. + +```bash +CUDA_VISIBLE_DEVICES= python trainer-program.py ... +``` + + + +As with any environment variable, they can be exported instead of being added to the command line. However, this is not recommended because it can be confusing if you forget how the environment variable was setup and you end up using the wrong GPUs. Instead, it is common practice to set the environment variable for a specific training run on the same command line. + + + +`CUDA_DEVICE_ORDER` is an alternative environment variable you can use to control how the GPUs are ordered. You can either order them by: + +1. PCIe bus ID's that matches the order of [`nvidia-smi`](https://developer.nvidia.com/nvidia-system-management-interface) and [`rocm-smi`](https://rocm.docs.amd.com/projects/rocm_smi_lib/en/latest/.doxygen/docBin/html/index.html) for NVIDIA and AMD GPUs respectively + +```bash +export CUDA_DEVICE_ORDER=PCI_BUS_ID +``` + +2. GPU compute ability + +```bash +export CUDA_DEVICE_ORDER=FASTEST_FIRST +``` + +The `CUDA_DEVICE_ORDER` is especially useful if your training setup consists of an older and newer GPU, where the older GPU appears first, but you cannot physically swap the cards to make the newer GPU appear first. In this case, set `CUDA_DEVICE_ORDER=FASTEST_FIRST` to always use the newer and faster GPU first (`nvidia-smi` or `rocm-smi` still reports the GPUs in their PCIe order). Or you could also set `export CUDA_VISIBLE_DEVICES=1,0`. diff --git a/docs/source/en/trainer.md b/docs/source/en/trainer.md index cb5e2631a2b550..2c8ca7d3459e1a 100644 --- a/docs/source/en/trainer.md +++ b/docs/source/en/trainer.md @@ -256,6 +256,12 @@ NEFTune is disabled after training to restore the original embedding layer to av The [`Trainer`] class is powered by [Accelerate](https://hf.co/docs/accelerate), a library for easily training PyTorch models in distributed environments with support for integrations such as [FullyShardedDataParallel (FSDP)](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) and [DeepSpeed](https://www.deepspeed.ai/). + + +Learn more about FSDP sharding strategies, CPU offloading, and more with the [`Trainer`] in the [Fully Sharded Data Parallel](fsdp) guide. + + + To use Accelerate with [`Trainer`], run the [`accelerate.config`](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-config) command to set up training for your training environment. This command creates a `config_file.yaml` that'll be used when you launch your training script. For example, some example configurations you can setup are: diff --git a/tests/utils/test_doc_samples.py b/tests/utils/test_doc_samples.py index 953654537843ee..30f957774b51ab 100644 --- a/tests/utils/test_doc_samples.py +++ b/tests/utils/test_doc_samples.py @@ -60,7 +60,7 @@ def test_sdpa_support_list(self): doctext = f.read() doctext = doctext.split( - "For now, Transformers supports inference and training through SDPA for the following architectures:" + "For now, Transformers supports SDPA inference and training for the following architectures:" )[1] doctext = doctext.split("Note that FlashAttention can only be used for models using the")[0]