Skip to content
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 DDP RAM multiple-cache bug #3818

Closed
aprikyan opened this issue Jun 29, 2021 · 6 comments
Closed

Multi-GPU DDP RAM multiple-cache bug #3818

aprikyan opened this issue Jun 29, 2021 · 6 comments
Labels
bug Something isn't working Stale TODO

Comments

@aprikyan
Copy link

I'm trying to train on a >100K dataset with large image sizes (5000*5000). There's no results.txt in the runs/exp, so I'm not sure what information can I provide about the data.

🐛 Bug

As it says in the title, during the training it tries to cache the images again after they are cached. In this specific case it results in the memory overload, so I'll try it with more memory and report the results, but the question is, why does it happen at all?

To Reproduce (REQUIRED)

Input:

!python -m torch.distributed.launch --nproc_per_node 4 train.py --batch 24 --data ../dataset.yaml --weights yolov5l6.pt --img 1280 --device 0,1,2,3 --cache

Output:

*****************************************
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. 
*****************************************
train: weights=yolov5l6.pt, cfg=, data=../dataset.yaml, hyp=data/hyps/hyp.scratch.yaml, epochs=300, batch_size=24, img_size=[1280], rect=False, resume=False, nosave=False, notest=False, noautoanchor=False, evolve=False, bucket=, cache_images=True, image_weights=False, device=0,1,2,3, multi_scale=False, single_cls=False, adam=False, sync_bn=False, workers=8, project=runs/train, entity=None, name=exp, exist_ok=False, quad=False, linear_lr=False, label_smoothing=0.0, upload_dataset=False, bbox_interval=-1, save_period=-1, artifact_alias=latest, local_rank=0
github: Command 'git fetch && git config --get remote.origin.url' timed out after 5 seconds, for updates see https://github.com/ultralytics/yolov5
YOLOv5 🚀 v5.0-228-gae4261c torch 1.8.1+cu102 CUDA:0 (NVIDIA Tesla V100-PCIE-16GB, 16160.5MB)
                                              CUDA:1 (NVIDIA Tesla V100-PCIE-16GB, 16160.5MB)
                                              CUDA:2 (NVIDIA Tesla V100-PCIE-16GB, 16160.5MB)
                                              CUDA:3 (NVIDIA Tesla V100-PCIE-16GB, 16160.5MB)

Added key: store_based_barrier_key:1 to store for rank: 0
hyperparameters: lr0=0.01, lrf=0.2, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=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, mosaic=1.0, mixup=0.0
tensorboard: Start with 'tensorboard --logdir runs/train', view at http://localhost:6006/
2021-06-28 20:50:49.965071: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libnvinfer.so.6'; dlerror: libnvinfer.so.6: cannot open shared object file: No such file or directory
2021-06-28 20:50:49.965192: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libnvinfer_plugin.so.6'; dlerror: libnvinfer_plugin.so.6: cannot open shared object file: No such file or directory
2021-06-28 20:50:49.965210: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:30] Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
wandb: Currently logged in as: ... (use `wandb login --relogin` to force relogin)
2021-06-28 20:51:02.387590: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libnvinfer.so.6'; dlerror: libnvinfer.so.6: cannot open shared object file: No such file or directory
2021-06-28 20:51:02.387730: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libnvinfer_plugin.so.6'; dlerror: libnvinfer_plugin.so.6: cannot open shared object file: No such file or directory
2021-06-28 20:51:02.387751: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:30] Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.

CondaEnvException: Unable to determine environment

Please re-run this command with one of the following options:

* Provide an environment name via --name or -n
* Re-run this command inside an activated conda environment.

wandb: Tracking run with wandb version 0.10.32
wandb: Syncing run exp25
wandb: ⭐️ View project at ...
wandb: 🚀 View run at ...
wandb: Run data is saved locally in ...
wandb: Run `wandb offline` to turn off syncing.

Overriding model.yaml nc=80 with nc=3

                 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    156928  models.common.C3                        [128, 128, 3]                 
  3                -1  1    295424  models.common.Conv                      [128, 256, 3, 2]              
  4                -1  1   1611264  models.common.C3                        [256, 256, 9]                 
  5                -1  1   1180672  models.common.Conv                      [256, 512, 3, 2]              
  6                -1  1   6433792  models.common.C3                        [512, 512, 9]                 
  7                -1  1   3540480  models.common.Conv                      [512, 768, 3, 2]              
  8                -1  1   5611008  models.common.C3                        [768, 768, 3]                 
  9                -1  1   7079936  models.common.Conv                      [768, 1024, 3, 2]             
 10                -1  1   2624512  models.common.SPP                       [1024, 1024, [3, 5, 7]]       
 11                -1  1   9971712  models.common.C3                        [1024, 1024, 3, False]        
 12                -1  1    787968  models.common.Conv                      [1024, 768, 1, 1]             
 13                -1  1         0  torch.nn.modules.upsampling.Upsample    [None, 2, 'nearest']          
 14           [-1, 8]  1         0  models.common.Concat                    [1]                           
 15                -1  1   6200832  models.common.C3                        [1536, 768, 3, False]         
 16                -1  1    394240  models.common.Conv                      [768, 512, 1, 1]              
 17                -1  1         0  torch.nn.modules.upsampling.Upsample    [None, 2, 'nearest']          
 18           [-1, 6]  1         0  models.common.Concat                    [1]                           
 19                -1  1   2757632  models.common.C3                        [1024, 512, 3, False]         
 20                -1  1    131584  models.common.Conv                      [512, 256, 1, 1]              
 21                -1  1         0  torch.nn.modules.upsampling.Upsample    [None, 2, 'nearest']          
 22           [-1, 4]  1         0  models.common.Concat                    [1]                           
 23                -1  1    690688  models.common.C3                        [512, 256, 3, False]          
 24                -1  1    590336  models.common.Conv                      [256, 256, 3, 2]              
 25          [-1, 20]  1         0  models.common.Concat                    [1]                           
 26                -1  1   2495488  models.common.C3                        [512, 512, 3, False]          
 27                -1  1   2360320  models.common.Conv                      [512, 512, 3, 2]              
 28          [-1, 16]  1         0  models.common.Concat                    [1]                           
 29                -1  1   5807616  models.common.C3                        [1024, 768, 3, False]         
 30                -1  1   5309952  models.common.Conv                      [768, 768, 3, 2]              
 31          [-1, 12]  1         0  models.common.Concat                    [1]                           
 32                -1  1  10496000  models.common.C3                        [1536, 1024, 3, False]        
 33  [23, 26, 29, 32]  1     61536  models.yolo.Detect                      [3, [[19, 27, 44, 40, 38, 94], [96, 68, 86, 152, 180, 137], [140, 301, 303, 264, 238, 542], [436, 615, 739, 380, 925, 792]], [256, 512, 768, 1024]]
Model Summary: 638 layers, 76670944 parameters, 76670944 gradients, 116.5 GFLOPs

Transferred 824/832 items from yolov5l6.pt
Scaled weight_decay = 0.0005625000000000001
Optimizer groups: 141 .bias, 141 conv.weight, 137 other
train: Scanning '../labels/train' images and labels...108752 found, 0 missing, 0
train: WARNING: Ignoring corrupted image and/or label ../images/train/34232screenshot50725.png: negative labels
train: WARNING: Ignoring corrupted image and/or label ../images/train/79939screenshot402772.png: broken PNG file (bad header checksum in b'IDAT')
train: New cache created: ../labels/train.cache
train: Caching images (534.5GB): 100%|█| 108751/108751 [2:19:51<00:00, 12.96it/s
val: Scanning '../labels/val.cache' images and labels... 15000 found, 0 missing,val: WARNING: Ignoring corrupted image and/or label ../images/val/84378screenshot698968.png: negative labels
val: WARNING: Ignoring corrupted image and/or label ../images/val/84392screenshot700468.png: negative labels
val: Scanning '../labels/val.cache' images and labels... 15000 found, 0 missing,
val: Caching images (73.7GB): 100%|███████| 14998/14998 [45:27<00:00,  5.50it/s]
Plotting labels... 

autoanchor: Analyzing anchors... anchors/target = 2.47, Best Possible Recall (BPR) = 0.6307. Attempting to improve anchors, please wait...
autoanchor: WARNING: Extremely small objects found. 722 of 326080 labels are < 3 pixels in size.
autoanchor: Running kmeans for 12 anchors on 326080 points...
autoanchor: thr=0.25: 0.9987 best possible recall, 4.06 anchors past thr
autoanchor: n=12, img_size=1280, metric_all=0.235/0.737-mean/best, past_thr=0.528-mean: 26,5,  48,5,  85,10,  136,24,  176,37,  224,36,  302,41,  183,203,  178,378,  179,626,  761,209,  177,971
train: Scanning '../labels/train.cache' images and labels... 108752 found, 0 mis
train: Scanning '../labels/train.cache' images and labels... 108752 found, 0 mis
train: Scanning '../labels/train.cache' images and labels... 108752 found, 0 mis
autoanchor: Evolving anchors with Genetic Algorithm: fitness = 0.7838: 100%|█| 1
autoanchor: thr=0.25: 0.9978 best possible recall, 3.84 anchors past thr
autoanchor: n=12, img_size=1280, metric_all=0.233/0.784-mean/best, past_thr=0.544-mean: 26,5,  49,4,  151,9,  176,18,  232,27,  173,38,  179,85,  186,161,  181,284,  176,472,  172,893,  1174,239
train: Caching images (0.2GB):   0%|     | 44/108751 [00:35<29:10:26,  1.04it/s]autoanchor: New anchors saved to model. Update model *.yaml to use these anchors in the future.

train: Caching images (362.9GB):  68%|▋| 73844/108751 [4:33:20<59:14,  9.82it/s]Killing subprocess 22517
Killing subprocess 22518
Killing subprocess 22519
Killing subprocess 22520
Traceback (most recent call last):
  File "/anaconda/envs/azureml_py36/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/anaconda/envs/azureml_py36/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/anaconda/envs/azureml_py36/lib/python3.6/site-packages/torch/distributed/launch.py", line 340, in <module>
    main()
  File "/anaconda/envs/azureml_py36/lib/python3.6/site-packages/torch/distributed/launch.py", line 326, in main
    sigkill_handler(signal.SIGTERM, None)  # not coming back
  File "/anaconda/envs/azureml_py36/lib/python3.6/site-packages/torch/distributed/launch.py", line 301, in sigkill_handler
    raise subprocess.CalledProcessError(returncode=last_return_code, cmd=cmd)
subprocess.CalledProcessError: Command '['/anaconda/envs/azureml_py36/bin/python', '-u', 'train.py', '--local_rank=3', '--batch', '24', '--data', '../dataset.yaml', '--weights', 'yolov5l6.pt', '--img', '1280', '--device', '0,1,2,3', '--cache']' died with <Signals.SIGTERM: 15>.

Environment

  • Python version: 3.6
  • GPU: 4xV100
  • RAM: 440GB + 1T swap memory
@aprikyan aprikyan added the bug Something isn't working label Jun 29, 2021
@github-actions
Copy link
Contributor

github-actions bot commented Jun 29, 2021

👋 Hello @aprikyan, thank you for your interest in 🚀 YOLOv5! Please visit our ⭐️ Tutorials to get started, where you can find quickstart guides for simple tasks like Custom Data Training all the way to advanced concepts like Hyperparameter Evolution.

If this is a 🐛 Bug Report, please provide screenshots and minimum viable code to reproduce your issue, otherwise we can not help you.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset images, training logs, screenshots, and a public link to online W&B logging if available.

For business inquiries or professional support requests please visit https://www.ultralytics.com or email Glenn Jocher at glenn.jocher@ultralytics.com.

Requirements

Python 3.8 or later with all requirements.txt dependencies installed, including torch>=1.7. To install run:

$ pip install -r requirements.txt

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

CI CPU testing

If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training (train.py), testing (test.py), inference (detect.py) and export (export.py) on MacOS, Windows, and Ubuntu every 24 hours and on every commit.

@glenn-jocher
Copy link
Member

glenn-jocher commented Jun 29, 2021

@aprikyan your command looks fine. Cache should only happen once per split (once for train, once for val). I would avoid increasing swap file to accommodate --cache though, this is probably counterproductive.

I would restart your system with no swap and try to reproduce at a smaller --img 320 (uses less RAM) to verify that it is actually trying to cache twice. --cache with DDP is not part of our CI so this is untested. If the problem persists please let us know.

@github-actions
Copy link
Contributor

github-actions bot commented Jul 30, 2021

👋 Hello, this issue has been automatically marked as stale because it has not had recent activity. Please note it will be closed if no further activity occurs.

Access additional YOLOv5 🚀 resources:

Access additional Ultralytics ⚡ resources:

Feel free to inform us of any other issues you discover or feature requests that come to mind in the future. Pull Requests (PRs) are also always welcomed!

Thank you for your contributions to YOLOv5 🚀 and Vision AI ⭐!

@1757525671
Copy link

hello, I have the same problem, how can I solve it, thank you

@hukaixuan19970627
Copy link

I have met the same problem. ┭┮﹏┭┮

@glenn-jocher
Copy link
Member

glenn-jocher commented Mar 4, 2022

@1757525671 @hukaixuan19970627 @aprikyan I'm able to reproduce the multi-caching on DDP training bug. I'm not sure if there's a simple solution as the python -m torch.distributed.run command will actually call train.py once per RANK, and then each RANK will create its own trainloader, which will independently cache it's own images.

COCO training example, --cache --img 640 --data coco.yaml should only use 120G of RAM, but is using 240G on a 2x GPU training:

python -m torch.distributed.run --nproc_per_node 2 --master_port 4 train.py --data coco.yaml --batch 128 --weights '' --cfg yolov5l.yaml --epochs 300 --project YOLOv5_v61_official --name YOLOv5l --img 640 --hyp hyp.scratch-high.yaml --device 3,4 --cache

Screenshot 2022-03-04 at 10 50 24

If you guys have any ideas or discover a solution please let us know!

@glenn-jocher glenn-jocher changed the title Caching images twice on multi-GPU Multi-GPU DDP RAM multiple-cache bug Mar 4, 2022
davidsvaughn added a commit to davidsvaughn/yolov5-2021 that referenced this issue Dec 2, 2022
This is to address (and hopefully fix) this issue: Multi-GPU DDP RAM multiple-cache bug ultralytics#3818 (ultralytics#3818).  This was a very serious and "blocking" issue until I could figure out what was going on.  The problem was especially bad when running Multi-GPU jobs with 8 GPUs, RAM usage was 8x higher than expected (!), causing repeated OOM failures.  Hopefully this fix will help others.
DDP causes each RANK to launch it's own process (one for each GPU) with it's own trainloader, and its own RAM image cache.  The DistributedSampler used by DDP (https://github.com/pytorch/pytorch/blob/master/torch/utils/data/distributed.py) will feed only a subset of images (1/WORLD_SIZE) to each available GPU on each epoch, but since the images are shuffled between epochs, each GPU process must still cache all images.  So I created a subclass of DistributedSampler called SmartDistributedSampler that forces each GPU process to always sample the same subset (using modulo arithmetic with RANK and WORLD_SIZE) while still allowing random shuffling between epochs.  I don't believe this disrupts the overall "randomness" of the sampling, and I haven't noticed any performance degradation.  

Signed-off-by: davidsvaughn <davidsvaughn@gmail.com>
glenn-jocher added a commit that referenced this issue Jan 3, 2024
… issue (#10383)

* Update dataloaders.py

This is to address (and hopefully fix) this issue: Multi-GPU DDP RAM multiple-cache bug #3818 (#3818).  This was a very serious and "blocking" issue until I could figure out what was going on.  The problem was especially bad when running Multi-GPU jobs with 8 GPUs, RAM usage was 8x higher than expected (!), causing repeated OOM failures.  Hopefully this fix will help others.
DDP causes each RANK to launch it's own process (one for each GPU) with it's own trainloader, and its own RAM image cache.  The DistributedSampler used by DDP (https://github.com/pytorch/pytorch/blob/master/torch/utils/data/distributed.py) will feed only a subset of images (1/WORLD_SIZE) to each available GPU on each epoch, but since the images are shuffled between epochs, each GPU process must still cache all images.  So I created a subclass of DistributedSampler called SmartDistributedSampler that forces each GPU process to always sample the same subset (using modulo arithmetic with RANK and WORLD_SIZE) while still allowing random shuffling between epochs.  I don't believe this disrupts the overall "randomness" of the sampling, and I haven't noticed any performance degradation.  

Signed-off-by: davidsvaughn <davidsvaughn@gmail.com>

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update dataloaders.py

move extra parameter (rank) to end so won't mess up pre-existing positional args

* Update dataloaders.py

removing extra '#'

* Update dataloaders.py

sample from DDP index array (self.idx) in mixup mosaic

* Merging self.indices and self.idx (DDP indices) into single attribute (self.indices).
Also adding SmartDistributedSampler to segmentation dataloader

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Multiply GB displayed by WORLD_SIZE

---------

Signed-off-by: davidsvaughn <davidsvaughn@gmail.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
pleb631 pushed a commit to pleb631/yolov5 that referenced this issue Jan 6, 2024
… issue (ultralytics#10383)

* Update dataloaders.py

This is to address (and hopefully fix) this issue: Multi-GPU DDP RAM multiple-cache bug ultralytics#3818 (ultralytics#3818).  This was a very serious and "blocking" issue until I could figure out what was going on.  The problem was especially bad when running Multi-GPU jobs with 8 GPUs, RAM usage was 8x higher than expected (!), causing repeated OOM failures.  Hopefully this fix will help others.
DDP causes each RANK to launch it's own process (one for each GPU) with it's own trainloader, and its own RAM image cache.  The DistributedSampler used by DDP (https://github.com/pytorch/pytorch/blob/master/torch/utils/data/distributed.py) will feed only a subset of images (1/WORLD_SIZE) to each available GPU on each epoch, but since the images are shuffled between epochs, each GPU process must still cache all images.  So I created a subclass of DistributedSampler called SmartDistributedSampler that forces each GPU process to always sample the same subset (using modulo arithmetic with RANK and WORLD_SIZE) while still allowing random shuffling between epochs.  I don't believe this disrupts the overall "randomness" of the sampling, and I haven't noticed any performance degradation.  

Signed-off-by: davidsvaughn <davidsvaughn@gmail.com>

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update dataloaders.py

move extra parameter (rank) to end so won't mess up pre-existing positional args

* Update dataloaders.py

removing extra '#'

* Update dataloaders.py

sample from DDP index array (self.idx) in mixup mosaic

* Merging self.indices and self.idx (DDP indices) into single attribute (self.indices).
Also adding SmartDistributedSampler to segmentation dataloader

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Multiply GB displayed by WORLD_SIZE

---------

Signed-off-by: davidsvaughn <davidsvaughn@gmail.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working Stale TODO
Projects
None yet
Development

No branches or pull requests

4 participants