-
-
Notifications
You must be signed in to change notification settings - Fork 16.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Multi-GPU Training 🌟 #475
Comments
I suggest we use
I suggest we should explictly make it clear that
The tutorial is excellent! Good job! |
This comment has been minimized.
This comment has been minimized.
Hello @feizhouxiaozhu , I think this may be because you are running multiple trainings at a time, and they are communicating to the same port. To fix this, you can run in a different port. $ python -m torch.distributed.launch --master_port 42342 --nproc_per_node 2 ... Please tell me if this fixed the problem. If it doesn't, can you tell us how to replicate this problem? |
Hmm, I'm not sure why that is. @feizhouxiaozhu , could you try to re-clone the repo then try again? If error still occurs, could you try to run on coco128? Run the code below in terminal. cd yolov5
python3 -c "from utils.google_utils import *; gdrive_download('1n_oKgR81BJtqk75b00eAjdv03qVCQn2f', 'coco128.zip')" && mv -n ./coco128 ../
export PYTHONPATH="$PWD"
python -m torch.distributed.launch --master_port 9990 --nproc_per_node 2 train.py --weights yolov5s.pt --cfg yolov5s.yaml --epochs 1 --img 320 I'm currently running 8 GPU DDP custom data training, and there is no issue. Edit: Reply was removed. @feizhouxiaozhu , is the problem solved? |
Excellent guide guys, thank you so much! I was training on a DGX1 and was wondering why there wasn't much of a speed difference. |
@cesarandreslopez oh wow, lucky you. Are you seeing faster speeds now with the updated multi gpu training? |
@glenn-jocher in DataParallel model, every Epoch, with about 51000 images in yolov5l.yaml was taking on the DGX1 about 6 and a half minutes. on DistributedDataParallel Mode with SyncBatchNorm I am seeing about 3 minutes and 10 seconds, so quite an improvement. I've seen no improvement in Testing speed. On @NanoCode012's guide there is this note:
Based on that I assumed that batch size could be something like --batch 1024, (128 per GPU), but I kept getting Cuda out of memory after an epoch was completed and it started to test, so I eventually just went with --batch 128. Apparent GPU use during training and testing.During training, GPU 0 seems to have a considerably higher RAM use than other GPUS (which limits the batch size to be around the same that one GPU could handle). The processing itself seems distributed on all GPUs GPU consumption during testing looks like this, where GPU 0 has very high memory use but it doesn't seem to process while the other 7 GPUS seem busy with the amount of memory expected for a batch of that size: Our training size for this example is about 51000 images and our testing sample is about 5100. Testing takes about 4 minutes and a half, an epoch on training takes about 3 minutes and 10 seconds Given the amount of time this spends on testing I am wondering if it is possible or even useful to set testing every n epochs. We are currently studying up on this repository and will understand it enough soon to be able to offer PRs. @glenn-jocher Happy to provide you remote access to the machine for your tests and so on. It's the least we can do! Just PM me. |
Hi @cesarandreslopez , nice numbers! The reason GPU 0 has higher memory is because it has to communicate with other GPUs to coordinate. In my test however, I don’t see that vast of a difference in GPU memory like you do. The latest one is 31GB (GPU 0) and 20 GB (others). Maybe SynBN is increasing GPU load or dataloaders for testing(?). Batch size is indeed divided evenly. Is it possible to run 128 batch size on your single GPU because that is quite large for yolov5l. Testing is done on only 1 GPU(GPU0 tests , other gpu continue train) , so that may be why you experience slow testing times. It’s is currently being worked on to use multiple GPUs there. It is an interesting concept to test every n epochs and can certainly be done. However, maybe randomness will cause you to miss the “best” epoch, so I’m not sure if it’s good. Edit: If you would like to do so, it’s on line 339 in Train.py, add a (epoch%interval==0) condition Edit2: How is speed without SynBN? Since the individual batch size is around 128/8 > 8, I’m not sure if accuracy would be affected. Edit3: If you have multiple machines you want to run this training on, there is an experimental PR you could try. |
@cesarandreslopez ok got it, thanks for the feedback. I think I know why your testing is CUDA OOM. Before the DDP updates train and test.py shared the same batch-size (default 32), it seems likely this is still the case, except that test.py is inheriting global batch size instead of local batch size. So I suspect you should be able to train with much larger batch sizes once this bug is fixed. @NanoCode012 does that make sense about the global vs local batch sizes being passed to test.py? Testing every n epochs is a good idea. You can currently use python test.py --notest to train without testing until the very final epoch, but we don't have a middle ground. Testing may not benefit as much from multi-gpu compared to training, because NMS ops run sequentially rather than in parallel, and tend to dominate testing time. An alternative to testing every n epochs is simply to supply a higher --conf-thres to test at. Default is 0.001, perhaps setting to 0.01 will halve your testing time. That's a very generous offer! I'm pretty busy these days so I can't take you up on it immediately, but I'll keep that in mind in the future, thank you! It would definitely be nice to have access to something like that. |
@glenn-jocher , I just noticed that! That may be why the memory is so different. But now it’s up to optimizations. For small “total batch size”, it makes sense to pass in the entire thing. For large “total”, it doesn’t make sense. I think one easy solution is to let user pass in one argument “—test-total”, to test their total batch size vs their divided batchsize. But it can get confusing for newcomers. Edit: What do you think? |
@NanoCode012 if we replace Lines 191 to 196 in fd532d9
And L341 would that solve @cesarandreslopez issue about testing OOM? Lines 339 to 348 in fd532d9
|
If we do so, datasets for testing could take num_gpu times longer. (I remember training/testing with total batchsize 16 for coco taking 1h) . I think giving user an option is good, but we should set test to use totalbatchsize to be on by default.. Only when user has OOM, should they configure it. “—notest—total” sounds good? |
@NanoCode012 ok got it. I think the most common use case is for users to maximize training cuda mem, so since test.py is currently restricted to single-gpu it would make sense to default it to batch_size rather than total_batch_size. But I suppose we should wait for @MagicFrogSJTU work on test.py before really modifying, since it will get a makeover shortly here. I think it's best to try and simplify the options when possible so it 'just works' as steve jobs would say, so let's avoid adding extra arguments if possible. @cesarandreslopez I think for the time being you could apply the L194 and L341 fix described above, we have a few more significant PRs due in the coming week, so a more permanent fix for this should be included in those. |
@glenn-jocher |
@glenn-jocher please note that when --notest is used on the current master branch it will crash after completing the first epoch.
I tried doing a touch results.txt under the /runs/expoN/ folder that will avoid the error above, but then a new one will appear:
so adding --notest to the command above, in yolov5 will not work right now. (this does work on yolov3 on previous tests). Edit 1: @NanoCode012 if I follow your suggestion:
The same error describe here as --notest will appear. |
@cesarandreslopez should be fixed following PR #518. Tested on single-GPU and CPU. |
hi! @glenn-jocher for multi-gpu training, if using smaller batch size than 64, could you suggest the hyperparameter to adjust like the learning rate? |
Internally, batch size is kept at least 64. Gradient accumulation will be used if a batch size smaller than 64 is given. Therefore, no adjust is needed if you use a smaller batch size. |
Hello @liumingjune, could you provide us the exact line you used? EDIT: Also, did you use the latest repo? I think this can be the reason. |
Thank you for your reply. My command line is python -m torch.distributed.launch --nproc_per_node 4 train. py --device 0,1,2,3 |
Hi @liumingjune , could you try to I ran git clone https://github.com/ultralytics/yolov5.git && cd yolov5
python -m torch.distributed.launch --nproc_per_node 4 train.py --device 0,1,2,3 and there were no problems. |
OK. I will try. Maybe that's the reason. I will try. My version is a clone of Yolov5 when it first appeared.Thanks a lot! |
Hello, I want to know the difference between the current version and the version just released before, because I find that the form of data set preparation is different. The previous one is to prepare the data set path and the training file, verify the file. I need to manually separate out the training data and the validation data. This is not friendly to large data volumes. |
Just to confirm - so if I choose a batch size of 8 on the train.py arguments, then if I'm using 4 GPUs then the model is theoretically backpropagating over 2 examples every step and the final results we see are for a model trained with a batch size of 2, or does the model gather the gradients together at every step to get the result from each GPU and backpropagate with a batch size of 8? |
@glenn-jocher Training with
The hardware is AWS g5.12xlarge with 4 GPU, training starts relatively fast but gets slower over time, it crashes with this error at after some epochs (I've seen at epoch 6, 7 and 9 with a dataset size of 70k with batch size 384). |
hi want to run yolov5 with qualcomm adreno GPU is it possible ??? |
Hi @glenn-jocher, |
Hi guys! I am using YOLOV5 for training and up to now I had only one GPU available. I recently integrated a second (identical) GPU in my machine and I try to run my code with Multi-GPU training and especially in DistributedDataParallel mode, which is currently recommended. I use a Jupyter notebook to run my experiments. Up to now I had been using the following code snippet: import train
opt = {
'weights': f"yolov5{YOLO_SIZE}.pt",
'cfg': '',
'data': CONF_FILE_PATH,
'epochs': EPOCHS,
'batch_size': BATCH_SIZE,
'imgsz': IMG_SIZE,
'rect': False,
'resume': False,
'nosave': False,
'noval': False,
'noautoanchor': False,
'noplots': False,
'bucket': '',
'cache': None,
'image_weights': False,
'multi_scale': False,
'nproc_per_node': 2,
'single_cls': False,
'optimizer': 'SGD',
'sync_bn': False,
'workers': 8,
'project': TRAIN_PATH,
'name': MODEL_NAME,
'exist_ok': True,
'quad': False,
'cos_lr': False,
'label_smoothing': 0.0,
'patience': PATIENCE,
'freeze': [0],
'save_period': -1,
'seed': SEED,
'local_rank': -1,
'entity': None,
'upload_dataset': False,
'bbox_interval': -1,
'artifact_alias': 'latest',
'device': ''
}
train.main(argparse.Namespace(**opt)) Currently, I use the same opt dictionary with the only deviation being the device value as described in https://docs.ultralytics.com/yolov5/tutorials/multi_gpu_training/#multi-gpu-distributeddataparallel-mode-recommended, where I set device to '0,1'. I have a doubt on whether it is right or wrong. The code I currently run is: import torch.distributed.run as dist_run
dist_run.main(train.main(argparse.Namespace(**opt)), nproc_per_node=2) The code runs but I do not seem to get parallelization. I do not want to run the process from the command window as suggested in the link above. Does anybody have any idea on how I would actually get parallel execution in the context I am describing? My code is currently running properly in this setting - but I get no acceleration compared to the single GPU setting - and in the end of the execution I get the error in the image below: |
📚 This guide explains how to properly use multiple GPUs to train a dataset with YOLOv5 🚀 on single or multiple machine(s). UPDATED 25 December 2022.
Before You Start
Clone repo and install requirements.txt in a Python>=3.7.0 environment, including PyTorch>=1.7. Models and datasets download automatically from the latest YOLOv5 release.
💡 ProTip! Docker Image is recommended for all Multi-GPU trainings. See Docker Quickstart Guide
💡 ProTip!
torch.distributed.run
replacestorch.distributed.launch
in PyTorch>=1.9. See docs for details.Training
Select a pretrained model to start training from. Here we select YOLOv5s, the smallest and fastest model available. See our README table for a full comparison of all models. We will train this model with Multi-GPU on the COCO dataset.
Single GPU
Multi-GPU DataParallel Mode (⚠️ not recommended)
You can increase the
device
to use Multiple GPUs in DataParallel mode.This method is slow and barely speeds up training compared to using just 1 GPU.
Multi-GPU DistributedDataParallel Mode (✅ recommended)
You will have to pass
python -m torch.distributed.run --nproc_per_node
, followed by the usual arguments.--nproc_per_node
specifies how many GPUs you would like to use. In the example above, it is 2.--batch
is the total batch-size. It will be divided evenly to each GPU. In the example above, it is 64/2=32 per GPU.The code above will use GPUs
0... (N-1)
.Use specific GPUs (click to expand)
You can do so by simply passing
--device
followed by your specific GPUs. For example, in the code below, we will use GPUs2,3
.$ python -m torch.distributed.run --nproc_per_node 2 train.py --batch 64 --data coco.yaml --cfg yolov5s.yaml --weights '' --device 2,3
Use SyncBatchNorm (click to expand)
SyncBatchNorm could increase accuracy for multiple gpu training, however, it will slow down training by a significant factor. It is only available for Multiple GPU DistributedDataParallel training.
It is best used when the batch-size on each GPU is small (<= 8).
To use SyncBatchNorm, simple pass
--sync-bn
to the command like below,$ python -m torch.distributed.run --nproc_per_node 2 train.py --batch 64 --data coco.yaml --cfg yolov5s.yaml --weights '' --sync-bn
Use Multiple machines (click to expand)
This is only available for Multiple GPU DistributedDataParallel training.
Before we continue, make sure the files on all machines are the same, dataset, codebase, etc. Afterwards, make sure the machines can communicate to each other.
You will have to choose a master machine(the machine that the others will talk to). Note down its address(
master_addr
) and choose a port(master_port
). I will usemaster_addr = 192.168.1.1
andmaster_port = 1234
for the example below.To use it, you can do as the following,
where
G
is number of GPU per machine,N
is the number of machines, andR
is the machine number from0...(N-1)
.Let's say I have two machines with two GPUs each, it would be
G = 2
,N = 2
, andR = 1
for the above.Training will not start until all
N
machines are connected. Output will only be shown on master machine!Notes
--batch
must be a multiple of the number of GPUs.RuntimeError: Address already in use
, it could be because you are running multiple trainings at a time. To fix this, simply use a different port number by adding--master_port
like below,Results
DDP profiling results on an AWS EC2 P4d instance with 8x A100 SXM4-40GB for YOLOv5l for 1 COCO epoch.
Profiling code
A100
device0 (G)
train
val
FAQ
If an error occurs, please read the checklist below first! (It could save your time)
Checklist (click to expand)
If you went through all the above, feel free to raise an Issue by giving as much detail as possible following the template.
Environments
YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):
Status
If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training, validation, inference, export and benchmarks on MacOS, Windows, and Ubuntu every 24 hours and on every commit.
Credits
I would like to thank @MagicFrogSJTU, who did all the heavy lifting, and @glenn-jocher for guiding us along the way.
The text was updated successfully, but these errors were encountered: