Debian Codegraph @

docs/source/basic_tutorials/troubleshooting.md

raw
1 <!--Copyright 2023 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 contain specific syntax for our doc-builder (similar to MDX) that may not be
13 rendered properly in your Markdown viewer.
14 -->
15
16 # Troubleshoot
17
18 This guide provides solutions to some issues you might encounter when using Accelerate. Not all errors are covered because Accelerate is an active library that is continuously evolving and there are many different use cases and distributed training setups. If the solutions described here don't help with your specific error, please take a look at the [Ask for help](#ask-for-help) section to learn where and how to get help.
19
20 ## Logging
21
22 Logging can help you identify where an error is coming from. In a distributed setup with multiple processes, logging can be a challenge, but Accelerate provides the [`~accelerate.logging`] utility to ensure logs are synchronized.
23
24 To troubleshoot an issue, use [`~accelerate.logging`] instead of the standard Python [`logging`](https://docs.python.org/3/library/logging.html#module-logging) module. Set the verbosity level (`INFO`, `DEBUG`, `WARNING`, `ERROR`, `CRITICAL`) with the `log_level` parameter, and then you can either:
25
26 1. Export the `log_level` as the `ACCELERATE_LOG_LEVEL` environment variable.
27 2. Pass the `log_level` directly to `get_logger`.
28
29 For example, to set `log_level="INFO"`:
30
31 ```py
32 from accelerate.logging import get_logger
33
34 logger = get_logger(__name__, log_level="DEBUG")
35 ```
36
37 By default, the log is called on main processes only. To call it on all processes, pass `main_process_only=False`.
38 If a log should be called on all processes and in order, also pass `in_order=True`.
39
40 ```py
41 from accelerate.logging import get_logger
42
43 logger = get_logger(__name__, log_level="DEBUG")
44 # log all processes
45 logger.debug("thing_to_log", main_process_only=False)
46 # log all processes in order
47 logger.debug("thing_to_log", main_process_only=False, in_order=True)
48 ```
49
50 ## Hanging code and timeout errors
51
52 There can be many reasons why your code is hanging. Let's take a look at how to solve some of the most common issues that can cause your code to hang.
53
54 ### Mismatched tensor shapes
55
56 Mismatched tensor shapes is a common issue that can cause your code to hang for a significant amount of time on a distributed setup.
57
58 When running scripts in a distributed setup, functions such as [`Accelerator.gather`] and [`Accelerator.reduce`] are necessary to grab tensors across devices to collectively perform operations on them. These (and other) functions rely on `torch.distributed` to perform a `gather` operation, which requires tensors to have the **exact same shape** across all processes. When the tensor shapes don't match, your code hangs and you'll eventually hit a timeout exception.
59
60 You can use Accelerate's operational debug mode to immediately catch this issue. We recommend enabling this mode during the `accelerate config` setup, but you can also enable it from the CLI, as an environment variable, or by manually editing the `config.yaml` file.
61
62 <hfoptions id="mismatch">
63 <hfoption id="CLI">
64
65 ```bash
66 accelerate launch --debug {my_script.py} --arg1 --arg2
67 ```
68
69 </hfoption>
70 <hfoption id="environment variable">
71
72 If enabling debug mode as an environment variable, you don't need to call `accelerate launch`.
73
74 ```bash
75 ACCELERATE_DEBUG_MODE="1" torchrun {my_script.py} --arg1 --arg2
76 ```
77
78 </hfoption>
79 <hfoption id="config.yaml">
80
81 Add `debug: true` to your `config.yaml` file.
82
83 ```yaml
84 compute_environment: LOCAL_MACHINE
85 debug: true
86 ```
87
88 </hfoption>
89 </hfoptions>
90
91 Once you enable debug mode, you should get a traceback that points to the tensor shape mismatch issue.
92
93 ```py
94 Traceback (most recent call last):
95 File "/home/zach_mueller_huggingface_co/test.py", line 18, in <module>
96 main()
97 File "/home/zach_mueller_huggingface_co/test.py", line 15, in main
98 broadcast_tensor = broadcast(tensor)
99 File "/home/zach_mueller_huggingface_co/accelerate/src/accelerate/utils/operations.py", line 303, in wrapper
100 accelerate.utils.operations.DistributedOperationException:
101
102 Cannot apply desired operation due to shape mismatches. All shapes across devices must be valid.
103
104 Operation: `accelerate.utils.operations.broadcast`
105 Input shapes:
106 - Process 0: [1, 5]
107 - Process 1: [1, 2, 5]
108 ```
109
110 ### Early stopping
111
112 For early stopping in distributed training, if each process has a specific stopping condition (e.g. validation loss), it may not be synchronized across all processes. As a result, a break can happen on process 0 but not on process 1 which will cause your code to hang indefinitely until a timeout occurs.
113
114 If you have early stopping conditionals, use the `set_trigger` and `check_trigger` methods to make sure all the processes
115 are ended correctly.
116
117 ```py
118 # Assume `should_do_breakpoint` is a custom-defined function that returns a conditional,
119 # and that conditional might be true only on process 1
120 if should_do_breakpoint(loss):
121 accelerator.set_trigger()
122
123 # Later in the training script when we need to check for the breakpoint
124 if accelerator.check_trigger():
125 break
126 ```
127
128 ### Low kernel versions on Linux
129
130 On Linux with kernel version < 5.5, hanging processes have been reported. To avoid this problem, upgrade your system to a later kernel version.
131
132 ### MPI
133
134 If your distributed CPU training job using MPI is hanging, ensure that you have
135 [passwordless SSH](https://www.open-mpi.org/faq/?category=rsh#ssh-keys) setup (using keys) between the nodes. This means
136 that for all nodes in your hostfile, you should be able to SSH from one node to another without being prompted for a password.
137
138 Next, try to run the `mpirun` command as a sanity check. For example, the command below should print out the
139 hostnames for each of the nodes.
140
141 ```bash
142 mpirun -f hostfile -n {number of nodes} -ppn 1 hostname
143 ```
144
145 ## Out-of-Memory
146
147 One of the most frustrating errors when it comes to running training scripts is hitting "Out-of-Memory" on devices like CUDA, XPU or CPU. The entire script needs to be restarted and any progress is lost.
148
149 To address this problem, Accelerate provides the [`find_executable_batch_size`] utility that is heavily based on [toma](https://github.com/BlackHC/toma).
150 This utility retries code that fails due to OOM (out-of-memory) conditions and automatically lowers batch sizes. For each OOM condition, the algorithm decreases the batch size by half and retries the code until it succeeds.
151
152 To use [`find_executable_batch_size`], restructure your training function to include an inner function with `find_executable_batch_size` and build your dataloaders inside it. At a minimum, this only takes 4 new lines of code.
153
154 <Tip warning={true}>
155
156 The inner function **must** take batch size as the first parameter, but we do not pass one to it when called. The wrapper will handle this for you. Any object (models, optimizers) that consumes device memory and is passed to the [`Accelerator`] also **must** be declared inside the inner function.
157
158 </Tip>
159
160 ```diff
161 def training_function(args):
162 accelerator = Accelerator()
163
164 + @find_executable_batch_size(starting_batch_size=args.batch_size)
165 + def inner_training_loop(batch_size):
166 + nonlocal accelerator # Ensure they can be used in our context
167 + accelerator.free_memory() # Free all lingering references
168 model = get_model()
169 model.to(accelerator.device)
170 optimizer = get_optimizer()
171 train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
172 lr_scheduler = get_scheduler(
173 optimizer,
174 num_training_steps=len(train_dataloader)*num_epochs
175 )
176 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
177 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
178 )
179 train(model, optimizer, train_dataloader, lr_scheduler)
180 validate(model, eval_dataloader)
181 + inner_training_loop()
182 ```
183
184 ## Non-reproducible results between device setups
185
186 If you changed the device setup and observe different model performance, it is likely you didn't update your script when moving from one setup to another. Even if you're using the same script with the same batch size, the results will still be different on a TPU, multi-GPU, and single GPU.
187
188 For example, if you were training on a single GPU with a batch size of 16 and you move to a dual GPU setup, you need to change the batch size to 8 to have the same effective batch size. This is because when training with Accelerate, the batch size passed to the dataloader is the **batch size per GPU**.
189
190 To make sure you can reproduce the results between the setups, make sure to use the same seed, adjust the batch size accordingly, and consider scaling the learning rate.
191
192 For more details and a quick reference for batch sizes, check out the [Comparing performance between different device setups](../concept_guides/performance) guide.
193
194 ## Performance issues on different GPUs
195
196 If your multi-GPU setup consists of different GPUs, you may encounter some performance issues:
197
198 - There may be an imbalance in GPU memory between the GPUs. In this case, the GPU with the smaller memory will limit the batch size or the size of the model that can be loaded onto the GPUs.
199 - If you are using GPUs with different performance profiles, the performance will be driven by the slowest GPU you are using because the other GPUs will have to wait for it to complete its workload.
200
201 Vastly different GPUs within the same setup can lead to performance bottlenecks.
202
203 ## Ask for help
204
205 If none of the solutions and advice here helped resolve your issue, you can always reach out to the community and Accelerate team for help.
206
207 - Ask for help on the Hugging Face forums by posting your question in the [Accelerate category](https://discuss.huggingface.co/c/accelerate/18). Make sure to write a descriptive post with relevant context about your setup and reproducible code to maximize the likelihood that your problem is solved!
208
209 - Post a question on [Discord](http://hf.co/join/discord), and let the team and the community help you.
210
211 - Create an Issue on the Accelerate [GitHub repository](https://github.com/huggingface/accelerate/issues) if you think you've found a bug related to the library. Include context regarding the bug and details about your distributed setup to help us better figure out what's wrong and how we can fix it.