yolov5 icon indicating copy to clipboard operation
yolov5 copied to clipboard

Multi-GPU Training 🌟

Open NanoCode012 opened this issue 4 years ago • 110 comments

📚 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.

git clone https://github.com/ultralytics/yolov5  # clone
cd yolov5
pip install -r requirements.txt  # install

đź’ˇ ProTip! Docker Image is recommended for all Multi-GPU trainings. See Docker Quickstart Guide Docker Pulls đź’ˇ ProTip! torch.distributed.run replaces torch.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.

YOLOv5 Models

Single GPU

$ python train.py  --batch 64 --data coco.yaml --weights yolov5s.pt --device 0

Multi-GPU DataParallel Mode (⚠️ not recommended)

You can increase the device to use Multiple GPUs in DataParallel mode.

$ python train.py  --batch 64 --data coco.yaml --weights yolov5s.pt --device 0,1

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.

$ python -m torch.distributed.run --nproc_per_node 2 train.py --batch 64 --data coco.yaml --weights yolov5s.pt --device 0,1

--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 GPUs 2,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 use master_addr = 192.168.1.1 and master_port = 1234 for the example below.

To use it, you can do as the following,

# On master machine 0
$ python -m torch.distributed.run --nproc_per_node G --nnodes N --node_rank 0 --master_addr "192.168.1.1" --master_port 1234 train.py --batch 64 --data coco.yaml --cfg yolov5s.yaml --weights ''
# On machine R
$ python -m torch.distributed.run --nproc_per_node G --nnodes N --node_rank R --master_addr "192.168.1.1" --master_port 1234 train.py --batch 64 --data coco.yaml --cfg yolov5s.yaml --weights ''

where G is number of GPU per machine, N is the number of machines, and R is the machine number from 0...(N-1). Let's say I have two machines with two GPUs each, it would be G = 2 , N = 2, and R = 1 for the above.

Training will not start until all N machines are connected. Output will only be shown on master machine!

Notes

  • Windows support is untested, Linux is recommended.
  • --batch must be a multiple of the number of GPUs.
  • GPU 0 will take slightly more memory than the other GPUs as it maintains EMA and is responsible for checkpointing etc.
  • If you get 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,
$ python -m torch.distributed.run --master_port 1234 --nproc_per_node 2 ...

Results

DDP profiling results on an AWS EC2 P4d instance with 8x A100 SXM4-40GB for YOLOv5l for 1 COCO epoch.

Profiling code
# prepare
t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v "$(pwd)"/coco:/usr/src/coco $t
pip3 install torch==1.9.0+cu111 torchvision==0.10.0+cu111 -f https://download.pytorch.org/whl/torch_stable.html
cd .. && rm -rf app && git clone https://github.com/ultralytics/yolov5 -b master app && cd app
cp data/coco.yaml data/coco_profile.yaml

# profile
python train.py --batch-size 16 --data coco_profile.yaml --weights yolov5l.pt --epochs 1 --device 0 
python -m torch.distributed.run --nproc_per_node 2 train.py --batch-size 32 --data coco_profile.yaml --weights yolov5l.pt --epochs 1 --device 0,1   
python -m torch.distributed.run --nproc_per_node 4 train.py --batch-size 64 --data coco_profile.yaml --weights yolov5l.pt --epochs 1 --device 0,1,2,3  
python -m torch.distributed.run --nproc_per_node 8 train.py --batch-size 128 --data coco_profile.yaml --weights yolov5l.pt --epochs 1 --device 0,1,2,3,4,5,6,7
GPUs
A100
batch-size CUDA_mem
device0 (G)
COCO
train
COCO
val
1x 16 26GB 20:39 0:55
2x 32 26GB 11:43 0:57
4x 64 26GB 5:57 0:55
8x 128 26GB 3:09 0:57

FAQ

If an error occurs, please read the checklist below first! (It could save your time)

Checklist (click to expand)
  • Have you properly read this post?
  • Have you tried to reclone the codebase? The code changes daily.
  • Have you tried to search for your error? Someone may have already encountered it in this repo or in another and have the solution.
  • Have you installed all the requirements listed on top (including the correct Python and Pytorch versions)?
  • Have you tried in other environments listed in the "Environments" section below?
  • Have you tried with another dataset like coco128 or coco2017? It will make it easier to find the root cause.

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

YOLOv5 CI

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.

NanoCode012 avatar Jul 22 '20 11:07 NanoCode012

There will be multiple/redundant outputs. It does not affect training. This is a WIP.

I suggest we use will be fixed in the future instead of WIP. Many probably don't know what is WIP. By the way, explain all the abbreviations. We must assume Users know nothing!

Multiple GPUs DistributedDataParallel Mode (Recommended!!)

I suggest we should explictly make it clear that DDP is faster than DP. Use this title

Multiple GPUs DistributedDataParallel Mode (Faster than DP, Recommended!!)

The tutorial is excellent! Good job!

MagicFrogSJTU avatar Jul 22 '20 14:07 MagicFrogSJTU

Traceback (most recent call last): File "train.py", line 482, in train(hyp, tb_writer, opt, device) File "train.py", line 130, in train with torch_distributed_zero_first(local_rank): File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/contextlib.py", line 81, in enter return next(self.gen) File "/home/amax/objectdetection/yolov5/utils/utils.py", line 41, in torch_distributed_zero_first torch.distributed.barrier() File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/site-packages/torch/distributed/distributed_c10d.py", line 1485, in barrier work = _default_pg.barrier() RuntimeError: NCCL error in: /pytorch/torch/lib/c10d/ProcessGroupNCCL.cpp:514, unhandled system error, NCCL version 2.4.8 Traceback (most recent call last): File "train.py", line 482, in train(hyp, tb_writer, opt, device) File "train.py", line 130, in train with torch_distributed_zero_first(local_rank): File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/contextlib.py", line 81, in enter return next(self.gen) File "/home/amax/objectdetection/yolov5/utils/utils.py", line 41, in torch_distributed_zero_first torch.distributed.barrier() File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/site-packages/torch/distributed/distributed_c10d.py", line 1485, in barrier work = _default_pg.barrier() RuntimeError: NCCL error in: /pytorch/torch/lib/c10d/ProcessGroupNCCL.cpp:514, unhandled system error, NCCL version 2.4.8 Traceback (most recent call last): File "train.py", line 482, in train(hyp, tb_writer, opt, device) File "train.py", line 130, in train with torch_distributed_zero_first(local_rank): File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/contextlib.py", line 81, in enter return next(self.gen) File "/home/amax/objectdetection/yolov5/utils/utils.py", line 41, in torch_distributed_zero_first torch.distributed.barrier() File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/site-packages/torch/distributed/distributed_c10d.py", line 1485, in barrier work = _default_pg.barrier() RuntimeError: NCCL error in: /pytorch/torch/lib/c10d/ProcessGroupNCCL.cpp:514, unhandled system error, NCCL version 2.4.8 Traceback (most recent call last): File "train.py", line 482, in train(hyp, tb_writer, opt, device) File "train.py", line 130, in train with torch_distributed_zero_first(local_rank): File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/contextlib.py", line 81, in enter return next(self.gen) File "/home/amax/objectdetection/yolov5/utils/utils.py", line 41, in torch_distributed_zero_first torch.distributed.barrier() File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/site-packages/torch/distributed/distributed_c10d.py", line 1485, in barrier work = _default_pg.barrier() RuntimeError: NCCL error in: /pytorch/torch/lib/c10d/ProcessGroupNCCL.cpp:514, unhandled system error, NCCL version 2.4.8 Traceback (most recent call last): File "train.py", line 482, in train(hyp, tb_writer, opt, device) File "train.py", line 130, in train with torch_distributed_zero_first(local_rank): File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/contextlib.py", line 81, in enter return next(self.gen) File "/home/amax/objectdetection/yolov5/utils/utils.py", line 41, in torch_distributed_zero_first torch.distributed.barrier() File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/site-packages/torch/distributed/distributed_c10d.py", line 1485, in barrier work = _default_pg.barrier() RuntimeError: NCCL error in: /pytorch/torch/lib/c10d/ProcessGroupNCCL.cpp:514, unhandled system error, NCCL version 2.4.8 Traceback (most recent call last): File "train.py", line 482, in train(hyp, tb_writer, opt, device) File "train.py", line 130, in train with torch_distributed_zero_first(local_rank): File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/contextlib.py", line 81, in enter return next(self.gen) File "/home/amax/objectdetection/yolov5/utils/utils.py", line 41, in torch_distributed_zero_first torch.distributed.barrier() File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/site-packages/torch/distributed/distributed_c10d.py", line 1485, in barrier work = _default_pg.barrier() RuntimeError: NCCL error in: /pytorch/torch/lib/c10d/ProcessGroupNCCL.cpp:514, unhandled system error, NCCL version 2.4.8 Traceback (most recent call last): File "train.py", line 482, in train(hyp, tb_writer, opt, device) File "train.py", line 130, in train with torch_distributed_zero_first(local_rank): File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/contextlib.py", line 81, in enter return next(self.gen) File "/home/amax/objectdetection/yolov5/utils/utils.py", line 41, in torch_distributed_zero_first torch.distributed.barrier() File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/site-packages/torch/distributed/distributed_c10d.py", line 1485, in barrier work = _default_pg.barrier() RuntimeError: NCCL error in: /pytorch/torch/lib/c10d/ProcessGroupNCCL.cpp:514, unhandled system error, NCCL version 2.4.8 [email protected] Password for 'https://[email protected]@gitee.com': Using CUDA device0 _CudaDeviceProperties(name='GeForce RTX 2080 Ti', total_memory=11019MB) device1 _CudaDeviceProperties(name='GeForce RTX 2080 Ti', total_memory=11019MB) device2 _CudaDeviceProperties(name='GeForce RTX 2080 Ti', total_memory=11019MB) device3 _CudaDeviceProperties(name='GeForce RTX 2080 Ti', total_memory=11019MB) device4 _CudaDeviceProperties(name='GeForce RTX 2080 Ti', total_memory=11019MB) device5 _CudaDeviceProperties(name='GeForce RTX 2080 Ti', total_memory=11019MB) device6 _CudaDeviceProperties(name='GeForce RTX 2080 Ti', total_memory=11019MB) device7 _CudaDeviceProperties(name='GeForce RTX 2080 Ti', total_memory=11019MB)

Traceback (most recent call last): File "train.py", line 468, in dist.init_process_group(backend='nccl', init_method='env://') # distributed backend File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/site-packages/torch/distributed/distributed_c10d.py", line 393, in init_process_group store, rank, world_size = next(rendezvous_iterator) File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/site-packages/torch/distributed/rendezvous.py", line 172, in _env_rendezvous_handler store = TCPStore(master_addr, master_port, world_size, start_daemon, timeout) RuntimeError: Address already in use Traceback (most recent call last): File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/runpy.py", line 193, in _run_module_as_main "main", mod_spec) File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/site-packages/torch/distributed/launch.py", line 263, in main() File "/home/amax/anaconda3/envs/pytorch/lib/python3.6/site-packages/torch/distributed/launch.py", line 259, in main cmd=cmd) subprocess.CalledProcessError: Command '['/home/amax/anaconda3/envs/pytorch/bin/python', '-u', 'train.py', '--local_rank=7', '--batch-size', '64', '--data', 'data/7classes.yaml', '--cfg', 'models/yolov5s.yaml', '--weights', '']' returned non-zero exit status 1.

feizhouxiaozhu avatar Jul 24 '20 07:07 feizhouxiaozhu

store = TCPStore(master_addr, master_port, world_size, start_daemon, timeout)
RuntimeError: Address already in use

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. Using the example from above, add --master_port ####, where #### is a random port number.

$ 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?

NanoCode012 avatar Jul 24 '20 07:07 NanoCode012

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?

NanoCode012 avatar Jul 24 '20 08:07 NanoCode012

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 avatar Jul 24 '20 10:07 cesarandreslopez

@cesarandreslopez oh wow, lucky you. Are you seeing faster speeds now with the updated multi gpu training?

glenn-jocher avatar Jul 24 '20 17:07 glenn-jocher

@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:

--batch-size is now the Total batch-size. It will be divided evenly to each GPU. In the example above, it is 64/2=32 per GPU.

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

image

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:

image

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.

cesarandreslopez avatar Jul 25 '20 03:07 cesarandreslopez

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.

NanoCode012 avatar Jul 25 '20 03:07 NanoCode012

@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 avatar Jul 25 '20 03:07 glenn-jocher

@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 avatar Jul 25 '20 04:07 NanoCode012

@NanoCode012 if we replace total_batch_size with batch_size on L194: https://github.com/ultralytics/yolov5/blob/fd532d9ce3b025c1040ed9c7c3cf80fd7b0c39ae/train.py#L191-L196

And L341 would that solve @cesarandreslopez issue about testing OOM? https://github.com/ultralytics/yolov5/blob/fd532d9ce3b025c1040ed9c7c3cf80fd7b0c39ae/train.py#L339-L348

glenn-jocher avatar Jul 25 '20 04:07 glenn-jocher

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 avatar Jul 25 '20 04:07 NanoCode012

@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 avatar Jul 25 '20 04:07 glenn-jocher

@NanoCode012 does that make sense about the global vs local batch sizes being passed to test.py?

@glenn-jocher After my fix, the training.py would run parallel test and global_batch_size would be split into small local_batch_size in the test time just like the training time. Problem solved.

MagicFrogSJTU avatar Jul 25 '20 04:07 MagicFrogSJTU

@glenn-jocher please note that when --notest is used on the current master branch it will crash after completing the first epoch.

Traceback (most recent call last):
  File "train.py", line 469, in <module>
    train(hyp, tb_writer, opt, device)
  File "train.py", line 371, in train
    with open(results_file, 'r') as f:  # create checkpoint
FileNotFoundError: [Errno 2] No such file or directory: 'runs/exp0/results.txt'

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:

Traceback (most recent call last):
  File "train.py", line 469, in <module>
    train(hyp, tb_writer, opt, device)
  File "train.py", line 380, in train
    if (best_fitness == fi) and not final_epoch:
UnboundLocalError: local variable 'fi' referenced before assignment

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:

Edit: If you would like to do so, it’s on line 339 in Train.py, add a (epoch%interval==0) condition

The same error describe here as --notest will appear.

cesarandreslopez avatar Jul 25 '20 13:07 cesarandreslopez

@cesarandreslopez should be fixed following PR https://github.com/ultralytics/yolov5/pull/518. Tested on single-GPU and CPU.

glenn-jocher avatar Jul 25 '20 17:07 glenn-jocher

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?

twangnh avatar Jul 30 '20 03:07 twangnh

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.

MagicFrogSJTU avatar Jul 30 '20 03:07 MagicFrogSJTU

Hello, I have the following problem when using multi-GPU training, which is done according to your command line. Uploading IMG_20200730_202105.jpg… IMG_20200730_202118

#not working on multi-GPU training.

liumingjune avatar Jul 30 '20 13:07 liumingjune

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.

NanoCode012 avatar Jul 30 '20 13:07 NanoCode012

Hello @liumingjune, could you provide us the exact line you used? Looking at the screenshot, did you pass in --local_rank argument?

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 I have 4 GPUs totally.

liumingjune avatar Jul 30 '20 13:07 liumingjune

Hi @liumingjune , could you try to pull or clone the repo again? I saw that your hyp values are old, and train function is missing some arguments.

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.

NanoCode012 avatar Jul 30 '20 14:07 NanoCode012

Hi @liumingjune , could you try to pull or clone the repo again? I saw that your hyp values are old, and train function is missing some arguments.

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!

liumingjune avatar Jul 30 '20 14:07 liumingjune

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.

liumingjune avatar Aug 03 '20 01:08 liumingjune

@liumingjune I don't know exactly what you're referring to, but the full change history is available here https://github.com/ultralytics/yolov5/commits/master

glenn-jocher avatar Aug 03 '20 18:08 glenn-jocher

well, i got the same problem with @feizhouxiaozhu if I set `--nproc_per_node 6 or 8 ', 2 or 4 is OK.

python3 -m torch.distributed.launch --master_port 9999 --nproc_per_node 8 train.py --batch-size 256 --data data/shape.yaml --cfg models/yolov5x.yaml --weights ' '

subprocess.CalledProcessError: Command '['/usr/bin/python3', '-u', 'train.py', '--local_rank=7', '--batch-size', '256', '--data', 'data/shape.yaml', '--cfg', 'models/yolov5x.yaml', '--weights', '']' returned non-zero exit status 1.

Frank1126lin avatar Aug 17 '20 10:08 Frank1126lin

well, i got the same problem with @feizhouxiaozhu if I set `--nproc_per_node 6 or 8 ', 2 or 4 is OK.

python3 -m torch.distributed.launch --master_port 9999 --nproc_per_node 8 train.py --batch-size 256 --data data/shape.yaml --cfg models/yolov5x.yaml --weights ' '

subprocess.CalledProcessError: Command '['/usr/bin/python3', '-u', 'train.py', '--local_rank=7', '--batch-size', '256', '--data', 'data/shape.yaml', '--cfg', 'models/yolov5x.yaml', '--weights', '']' returned non-zero exit status 1.

Hi @Frank1126lin , could you tell me where/when that error occured?

I ran the below(your code but on coco2017) on a new clone, and there were no issues till training epoch 1. Did you try to reclone?

python3 -m torch.distributed.launch --master_port 9999 --nproc_per_node 8 train.py --batch-size 256 --data data/coco.yaml --cfg models/yolov5x.yaml --weights ' '

@feizhouxiaozhu 's error is most likely due to an old clone as stated. Proper DDP training was added not too long ago.

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!

NanoCode012 avatar Aug 17 '20 11:08 NanoCode012

well, i got the same problem with @feizhouxiaozhu if I set --nproc_per_node 6 or 8 ', 2 or 4 is OK. python3 -m torch.distributed.launch --master_port 9999 --nproc_per_node 8 train.py --batch-size 256 --data data/shape.yaml --cfg models/yolov5x.yaml --weights ' ' subprocess.CalledProcessError: Command '['/usr/bin/python3', '-u', 'train.py', '--local_rank=7', '--batch-size', '256', '--data', 'data/shape.yaml', '--cfg', 'models/yolov5x.yaml', '--weights', '']' returned non-zero exit status 1.`

Hi @Frank1126lin , could you tell me where/when that error occured?

I ran the below(your code but on coco2017) on a new clone, and there were no issues till training epoch 1. Did you try to reclone?

python3 -m torch.distributed.launch --master_port 9999 --nproc_per_node 8 train.py --batch-size 256 --data data/coco.yaml --cfg models/yolov5x.yaml --weights ' '

@feizhouxiaozhu 's error is most likely due to an old clone as stated. Proper DDP training was added not too long ago.

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!

OK,thank you so much for your ans. I will try to reclone this repo and try it again. and annother question, when I use --nproc_per_node 4, it seems takes almost same time compare with single GPU training. just like code below. python3 -m torch.distributed.launch --nproc_per_node 4 train.py --batch-size 256 --data data/shape.yaml --cfg yolov5x.yaml --weights '' --epochs 2400 Optimizer stripped from runs/exp2/weights/last.pt, 177.4MB Optimizer stripped from runs/exp2/weights/best.pt, 177.4MB 2400 epochs completed in 2.726 hours.

Frank1126lin avatar Aug 18 '20 00:08 Frank1126lin

I got the same problem as below:

root@:~/ai/yolov5-0818# python3 -m torch.distributed.launch --master_port 9999  --nproc_per_node 8 train.py  --batch-size 128 --data shape.yaml --cfg yolov5l.yaml --weights '' --device 0,1,2,3,4,5,6,7
*****************************************
Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. 
*****************************************
Using CUDA device0 _CudaDeviceProperties(name='Tesla V100-PCIE-32GB', total_memory=32510MB)
           device1 _CudaDeviceProperties(name='Tesla V100-PCIE-32GB', total_memory=32510MB)
           device2 _CudaDeviceProperties(name='Tesla V100-PCIE-32GB', total_memory=32510MB)
           device3 _CudaDeviceProperties(name='Tesla V100-PCIE-32GB', total_memory=32510MB)
           device4 _CudaDeviceProperties(name='Tesla V100-PCIE-32GB', total_memory=32510MB)
           device5 _CudaDeviceProperties(name='Tesla V100-PCIE-32GB', total_memory=32510MB)
           device6 _CudaDeviceProperties(name='Tesla V100-PCIE-32GB', total_memory=32510MB)
           device7 _CudaDeviceProperties(name='Tesla V100-PCIE-32GB', total_memory=32510MB)

Namespace(adam=False, batch_size=16, bucket='', cache_images=False, cfg='./models/yolov5l.yaml', data='./data/shape.yaml', device='0,1,2,3,4,5,6,7', epochs=300, evolve=False, global_rank=0, hyp='data/hyp.scratch.yaml', img_size=[640, 640], local_rank=0, logdir='runs/', multi_scale=False, name='', noautoanchor=False, nosave=False, notest=False, rect=False, resume=False, single_cls=False, sync_bn=False, total_batch_size=128, weights='', workers=8, world_size=8)
Start Tensorboard with "tensorboard --logdir runs/", view at http://localhost:6006/
Hyperparameters {'lr0': 0.01, 'momentum': 0.937, 'weight_decay': 0.0005, 'giou': 0.05, 'cls': 0.5, 'cls_pw': 1.0, 'obj': 1.0, 'obj_pw': 1.0, 'iou_t': 0.2, 'anchor_t': 4.0, 'fl_gamma': 0.0, 'hsv_h': 0.015, 'hsv_s': 0.7, 'hsv_v': 0.4, 'degrees': 0.0, 'translate': 0.1, 'scale': 0.5, 'shear': 0.0, 'perspective': 0.0, 'flipud': 0.0, 'fliplr': 0.5, 'mixup': 0.0}

                 from  n    params  module                                  arguments                     
  0                -1  1      7040  models.common.Focus                     [3, 64, 3]                    
  1                -1  1     73984  models.common.Conv                      [64, 128, 3, 2]               
  2                -1  1    161152  models.common.BottleneckCSP             [128, 128, 3]                 
  3                -1  1    295424  models.common.Conv                      [128, 256, 3, 2]              
  4                -1  1   1627904  models.common.BottleneckCSP             [256, 256, 9]                 
  5                -1  1   1180672  models.common.Conv                      [256, 512, 3, 2]              
  6                -1  1   6499840  models.common.BottleneckCSP             [512, 512, 9]                 
  7                -1  1   4720640  models.common.Conv                      [512, 1024, 3, 2]             
  8                -1  1   2624512  models.common.SPP                       [1024, 1024, [5, 9, 13]]      
  9                -1  1  10234880  models.common.BottleneckCSP             [1024, 1024, 3, False]        
 10                -1  1    525312  models.common.Conv                      [1024, 512, 1, 1]             
 11                -1  1         0  torch.nn.modules.upsampling.Upsample    [None, 2, 'nearest']          
 12           [-1, 6]  1         0  models.common.Concat                    [1]                           
 13                -1  1   2823680  models.common.BottleneckCSP             [1024, 512, 3, False]         
 14                -1  1    131584  models.common.Conv                      [512, 256, 1, 1]              
 15                -1  1         0  torch.nn.modules.upsampling.Upsample    [None, 2, 'nearest']          
 16           [-1, 4]  1         0  models.common.Concat                    [1]                           
 17                -1  1    707328  models.common.BottleneckCSP             [512, 256, 3, False]          
 18                -1  1    590336  models.common.Conv                      [256, 256, 3, 2]              
 19          [-1, 14]  1         0  models.common.Concat                    [1]                           
 20                -1  1   2561536  models.common.BottleneckCSP             [512, 512, 3, False]          
 21                -1  1   2360320  models.common.Conv                      [512, 512, 3, 2]              
 22          [-1, 10]  1         0  models.common.Concat                    [1]                           
 23                -1  1  10234880  models.common.BottleneckCSP             [1024, 1024, 3, False]        
 24      [17, 20, 23]  1     37695  models.yolo.Detect                      [2, [[10, 13, 16, 30, 33, 23], [30, 61, 62, 45, 59, 119], [116, 90, 156, 198, 373, 326]], [256, 512, 1024]]
Model Summary: 335 layers, 4.73987e+07 parameters, 4.73987e+07 gradients
Optimizer groups: 110 .bias, 118 conv.weight, 107 other
Scanning labels ../shape/labels/train.cache (3 found, 0 missing, 0 empty, 0 duplicate, for 3 images): 3it [00:00, 5409.68it/s]
Scanning labels ../shape/labels/train.cache (3 found, 0 missing, 0 empty, 0 duplicate, for 3 images): 3it [00:00, 7362.73it/s]
Traceback (most recent call last):
  File "train.py", line 458, in <module>
Traceback (most recent call last):
  File "train.py", line 458, in <module>
    train(hyp, opt, device, tb_writer)
  File "train.py", line 167, in train
Traceback (most recent call last):
  File "train.py", line 458, in <module>
    ema.updates = start_epoch * nb // accumulate  # set EMA updates
AttributeError: 'NoneType' object has no attribute 'updates'
Traceback (most recent call last):
Traceback (most recent call last):
  File "train.py", line 458, in <module>
  File "train.py", line 458, in <module>
    train(hyp, opt, device, tb_writer)
  File "train.py", line 167, in train
    train(hyp, opt, device, tb_writer)
  File "train.py", line 167, in train
    ema.updates = start_epoch * nb // accumulate  # set EMA updates
AttributeError: 'NoneType' object has no attribute 'updates'
    ema.updates = start_epoch * nb // accumulate  # set EMA updates
AttributeError: 'NoneType' object has no attribute 'updates'
    train(hyp, opt, device, tb_writer)
    train(hyp, opt, device, tb_writer)
  File "train.py", line 167, in train
  File "train.py", line 167, in train
    ema.updates = start_epoch * nb // accumulate  # set EMA updates
    ema.updates = start_epoch * nb // accumulate  # set EMA updates
AttributeError: 'NoneType' object has no attribute 'updates'
AttributeError: 'NoneType' object has no attribute 'updates'
Traceback (most recent call last):
  File "train.py", line 458, in <module>
    train(hyp, opt, device, tb_writer)
  File "train.py", line 167, in train
Traceback (most recent call last):
  File "train.py", line 458, in <module>
    ema.updates = start_epoch * nb // accumulate  # set EMA updates
AttributeError: 'NoneType' object has no attribute 'updates'
    train(hyp, opt, device, tb_writer)
  File "train.py", line 167, in train
    ema.updates = start_epoch * nb // accumulate  # set EMA updates
AttributeError: 'NoneType' object has no attribute 'updates'

Analyzing anchors... anchors/target = 6.32, Best Possible Recall (BPR) = 1.0000
Image sizes 640 train, 640 test
Using 3 dataloader workers
Starting training for 300 epochs...
Traceback (most recent call last):
  File "train.py", line 458, in <module>
    train(hyp, opt, device, tb_writer)
  File "train.py", line 238, in train
    pbar = enumerate(dataloader)
  File "/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py", line 291, in __iter__
    return _MultiProcessingDataLoaderIter(self)
  File "/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py", line 764, in __init__
    self._try_put_index()
  File "/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py", line 994, in _try_put_index
    index = self._next_index()
  File "/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py", line 357, in _next_index
    return next(self._sampler_iter)  # may raise StopIteration
  File "/usr/local/lib/python3.6/dist-packages/torch/utils/data/sampler.py", line 208, in __iter__
    for idx in self.sampler:
  File "/usr/local/lib/python3.6/dist-packages/torch/utils/data/distributed.py", line 80, in __iter__
    assert len(indices) == self.total_size
AssertionError
Traceback (most recent call last):
  File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/usr/local/lib/python3.6/dist-packages/torch/distributed/launch.py", line 261, in <module>
    main()
  File "/usr/local/lib/python3.6/dist-packages/torch/distributed/launch.py", line 257, in main
    cmd=cmd)
subprocess.CalledProcessError: Command '['/usr/bin/python3', '-u', 'train.py', '--local_rank=7', '--batch-size', '128', '--data', 'shape.yaml', '--cfg', 'yolov5l.yaml', '--weights', '', '--device', '0,1,2,3,4,5,6,7']' returned non-zero exit status 1.

Frank1126lin avatar Aug 18 '20 09:08 Frank1126lin

Hi @Frank1126lin , regarding the ema error, I just created a fix for this at #775 and waiting for review. I am not as sure about the second error. Can you replicate this on coco dataset?

Edit: Also are there any errors in Single GPU mode?

For training time, I haven't done any test in a while, so I cannot say.

NanoCode012 avatar Aug 18 '20 10:08 NanoCode012