Skip to content

DLC 3.0: Minimal GPU usage #2639

Closed
Closed

Description

@roaldarbol

Is there an existing issue for this?

  • I have searched the existing issues

Bug description

I'm starting out with some tracking again, now with the new PyTorch backend. I'm analysing some massive videos, 2 hours at 60fps and dimensions w=1280, h=720. Currently I'm getting just over 7fps when I'm analysing videos. The issue is not that PyTorch is not registering the GPU - I had that issue (was getting 1.3fps before when torch.cuda.is_available() returned False, now it returns True), but even with the GPU being accessible, it's not really being used much, sitting at about 10%, and the Python thread running DLC is using less than 1% of that.

Operating System

Windows 10

DeepLabCut version

DLC 3.0.0rc1

DeepLabCut mode

single animal

Device type

Nvidia Quadro M5000, 8GB

Steps To Reproduce

  1. Install DLC 3.0.0rc1 as per the installation instructions for Windows.
  2. Start tracking videos
  3. Watch the GPU usage in the Task Manager

Relevant log output

No response

Anything else?

Here see the total GPU usage:
gpu-usage

Here, see that the Python process uses less than 1% GPU:
gpu-usage2

Again, this time from nvidia-smi, the memory usage is less than 10% (812Mb/8192Mb):
nvidia-smi

Code of Conduct

Activity

  1. roaldarbol commented on Jun 27, 2024

    @roaldarbol
    Author

    EDIT: Apologies for the tiny images, dunno whay they aren't any bigger... Hopefully you can somehwat make out what they say!

  2. changed the title [-]DLC 3.0: Little GPU usage[/-] [+]DLC 3.0: Minimal GPU usage[/+] on Jun 27, 2024
  3. roaldarbol commented on Jun 27, 2024

    @roaldarbol
    Author

    For reference, the GPU is heavily engaged during training:
    training-usage2
    training-usage

  4. roaldarbol commented on Jun 28, 2024

    @roaldarbol
    Author

    I've also followed the new installation steps to install the stable TF version. Currently I'm training a ResNet50 network on the same images, and the GPU process is running at ~20%. Will update once I can begin analysing videos.

  5. n-poulsen commented on Jul 2, 2024

    @n-poulsen
    Contributor

    @roaldarbol thanks for working on this! I'll take a look and get back to you

  6. roaldarbol commented on Jul 2, 2024

    @roaldarbol
    Author

    Sounds good, thanks @n-poulsen! Let me know whenever whatever you need from my side, can also run some tests if needed. :-)

  7. chz31 commented on Jul 22, 2024

    @chz31

    I also got a similar problem in both Windows 11 and WSL Ubuntu 22.04 with DLC 3.0 pytorch version. torch.cuda.is_available() returned True. It appears GPU was engaged during model training but not video analyzing. When I ran deeplabcut.analyze_videos, it was really slow and CPU usage was pushed to nearly 100%.

  8. roaldarbol commented on Jul 24, 2024

    @roaldarbol
    Author

    @n-poulsen Did you find time to have a look at this? (I can see from the commits that you guys a working hard, so no worries if not, just curious) :-)

  9. n-poulsen commented on Aug 5, 2024

    @n-poulsen
    Contributor

    Hey @roaldarbol - yes currently working on an improvement (should be out soon)! Could you let me know which model architecture you're using?

  10. roaldarbol commented on Aug 6, 2024

    @roaldarbol
    Author

    Sound great! I used a ResNet (it says net_type: resnet_50).

  11. slagathor69 commented on Aug 6, 2024

    @slagathor69

    For me to utilize my GPU I had to manually edit file:
    dlc-models-pytorch/iteration-0/yourexperimentMonthDay-trainset95shuffle1/pytorch_config.yaml

    and change

    'freeze_bn_stats': true
    

    to

    'freeze_bn_stats': false
    

    I also tried setting batch_size in this file and pose_cfg.yaml but found that it had no difference as DeepLabCut reverted back to batch_size of 2 for these processes regardless.

    Even passing torch_kwargs = {'batch_size': 2, 'freeze_bn_stats': False}, as a parameter to deeplabcut.train_network() made no difference.
    capital "False" is not error here, it would not accept "false"

    For me what finally ran successfully and utilized the GPU was editing the pytorch_config.yaml file then running

    deeplabcut.train_network(path_config_file,
                             batch_size = 2,
                             epochs = 1000,
                             save_epochs = 100)
    

    Using NVIDIA 4090 with 24GB of VRAM, I couldn't use higher batch_size than 2 here without it running out of VRAM for model hrnet_w48.

  12. n-poulsen commented on Aug 13, 2024

    @n-poulsen
    Contributor

    Hi @roaldarbol! This issue should have been addressed by #2708. You can increase the batch size when analyzing videos, which should boosts inference speed, and increases GPU usage. The default batch size for inference is taken from your project configuration file (there should be a batch_size key in there, with a default value of 8), but you can override that by passing the batch size as a parameter to the analyze_videos method:

    import deeplabcut
    
    deeplabcut.analyze_videos(
        config="/path/to/config.yaml",
        ...,
        batch_size=16,  # batch size for the pose model
        detector_batch_size=8,  # batch size for the detector for top-down models
    )
  13. 20 remaining items

  14. n-poulsen commented on Jan 27, 2025

    @n-poulsen
    Contributor

    While the object detector is running, could you print the output of the nvidia-smi (see this StackOverflow post on how to run the command on Windows) so I can see what's happening on your GPU?

  15. surjeets commented on Jan 30, 2025

    @surjeets

    @n-poulsen here is the output
    I also ran python -c "import torch; print(torch.version.cuda)" afterwards to just see if the cuda version shown with nvidi-smi (12.6) and the one I used to compile DLC (11.8) are same. Not sure if that could be the issue?
    I used a different cuda version for a different project.

    Image

  16. n-poulsen commented on Jan 30, 2025

    @n-poulsen
    Contributor

    Thanks @surjeets - perhaps the easiest way to try to fix this issue is through a clean DeepLabCut environment; could you create a new one with the most recent CUDA version so it matches your installation?

    conda create -n deeplabcut3 python=3.10
    conda activate deeplabcut3
    pip install "numpy<2"
    pip install torch torchvision --index-url https://download.pytorch.org/whl/cu126
    conda install -c conda-forge pytables==3.8.0
    pip install "git+https://github.com/DeepLabCut/DeepLabCut.git@pytorch_dlc#egg=deeplabcut[gui,modelzoo,wandb]"

    And try running the commands in this new deeplabcut3 environment

  17. frikyng commented on Jan 30, 2025

    @frikyng

    Hi all, I have been getting back to DLC and still wasn't happy with the overall performance of my system even though I thought I fixed it (see above). I have made an interesting observation!
    First of all when installing DLC into a new environment with instructions from this link. However, my GPU wasn't used at all even with the settings I identified above.

    FYI this is the output from nvidia-smi. Ihave CUDA 12.7 installed atm.
    Image

    Incidentally, I then ran python -c "import torch; print(torch.version.cuda)" it returned false, i.e. GPU not available! I then asked Claude and he suggested run conda install pytorch pytorch-cuda=11.8 -c pytorch -c nvidia, which I did in a fresh environment. After this I indeed got true for python -c "import torch; print(torch.cuda.is_available())" and the torch version from python -c "import torch; print(torch.version.cuda)". Great news.
    I then proceeded with the installation of DLC using conda install -c conda-forge pytables==3.8.0 and pip install "git+https://github.com/DeepLabCut/DeepLabCut.git@pytorch_dlc#egg=deeplabcut[gui,modelzoo,wandb]". This went well, except that at the end of the installation I got an output stating that a torch package got uninstalled.
    I then ran python -c "import torch; print(torch.cuda.is_available())" yet again and it returned false!

    Image

    Conclusion - there must be something in the installation that breaks my GPU usage.

    What do you think could cause this behaviour? I was thinking it may be necessary to downgrade my CUDA but Claude said that pytorch-cuda

    EDIT - I just saw the latest comment. I also tried with pytorch-cuda 12.1 but it's the same issue. Also I get that behaviour with the uninstalled torch package. I'll also try these new commands

  18. n-poulsen commented on Jan 30, 2025

    @n-poulsen
    Contributor

    @frikyng it seems the last command you ran (the one for which you shared the logs) uninstalled PyTorch 2.5.1 and installed PyTorch 2.6.0 instead, which means it would no longer be compatible with your GPU... I think it's possible that it did that because torchvision wasn't installed (but is needed by DeepLabCut) and it installed the latest torchvision. This will likely have installed PyTorch compiled for another CUDA version than 11.8, which is what was installed in your environment.

    PyTorch just deprecated conda installation (for release 2.6.0 this week), so I updated the installation docs in the pull request #2613 to install it through pip.

    You should be able to fix your conda environment by running:

    pip uninstall torch torchvision
    pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118

    Which will re-install the latest version of torch and torchvision for CUDA 11.8. But creating a new environment with the commands I shared above should also work.

  19. surjeets commented on Jan 30, 2025

    @surjeets

    @n-poulsen This is great! Thank you for your help in fixing this. It was such a silly mistake I should have looked at it earlier.
    All set now!

    Image

  20. n-poulsen commented on Jan 30, 2025

    @n-poulsen
    Contributor

    @surjeets awesome! glad I could help!

  21. frikyng commented on Jan 30, 2025

    @frikyng

    UPDATE

    Wow!! GPU is being used now. All I had to do is run the commands you posted. I see why the error may have come about with the other method I posted. Thanks for the help!

    Image

    One more question. In the training log in the console of the iterations in the log there is this message mentioning that you can increase the learning rate depending on the batch size. I suppose this is the one in runner->optimizer->params->lr?
    Also, I was wondering if there is a way of seeing the speed of the training similar to the tensorflow version? I just don't know what to expect performance wise and how to tweak my values.

    Image

    Lastly, @surjeets I saw earlier that you have an RTX4090 just like me. If I run the prediction with my current settings I get 8.6it/s. I am wondering if you can share your config file for me to compare. Also, what type of network are you using (e.g. resnet_50 or 101)?
    Edit2 - with resnet_50 I am getting about 30it/s. So still a bit slower than what you have shown given you'd be evaluating resnet_50

  22. n-poulsen commented on Jan 30, 2025

    @n-poulsen
    Contributor

    @frikyng exactly - generally, you want to increase your learning rate when increasing the batch size. there are some good resources (papers and StackOverflow posts) on how the learning rate should be scaled. However, note that a larger batch size when training on few images will likely mean you need to train for more epochs (as there will be fewer iterations which update the model parameters). In the example you're training here (with 38 training images and 2 test images), I wouldn't increase the batch size too much.

    To get the best possible performance out of your model, it's good to play around with the learning rate and scheduler a bit (you want to start with a larger learning rate, and after some epochs reduce it - choosing how to edit it is described in the docs (look at the scheduler).

    Are you training a single or multi-animal model? And which architecture are you using?

  23. frikyng commented on Jan 30, 2025

    @frikyng

    Thanks for the info! I think I'll just set the lr to 0.064 given what is mentioned in the post.
    The small number of frames is due to this just being a test data set. In the real thing I will have many more videos and loads of frames.

    In the final model I will use a single animal model with videos of different animals on a 2-photon setup. My plan is to train resnet_101 since intuitively I'd think it gives more robust results. Though idk how much better the _101 performance is than the _50 model. Are the any other architectures you'd recommend. I am attaching frames from the two angles I will analyse.

    image image
  24. n-poulsen commented on Jan 30, 2025

    @n-poulsen
    Contributor

    @frikyng I'd start by trying to train a resnet_50 and use that as a baseline (then I would train the resnet_101 and compare results - as it will be slower to analyze videos with, might as well see if it improves performance on the lighter model). I don't have "hard" numbers on this yet, but early results using cspnext_m have yielded very good results for me, and it also has the advantage of being faster to run inference with and train than a ResNet.

    I think 0.064 might also be a bit too big for the learning rate, and your model might diverge (this would be visible quickly, with the loss "exploding"). I think setting it to 0.001 would be a good place to start

  25. frikyng commented on Jan 30, 2025

    @frikyng

    Ok great info. I'll try all these configs.

    One more Q - I tried replicating the results of @surjeets and trained a resnet_50 on my test data set. This was already faster than with the resnet_101 I tried inferencing with before. Then I set the batch_size of the video analysis to 8 and then 16. This actually yielded quite nice results, i.e. 116it/s inference speed ...for both. I also saw that there are 2 CPU cores that are maxed out. This got me thinking if there is a bottle neck (potentially due to data_loader workers?). Interestingly, the same behaviour also seems to be true for @surjeets as his GPU usage seems to run similar a similar job. Also, he has a i9-13900 and I an i9-14900. Do you know what could be holding the GPU back here?

    Also, what train results should I target? I am talking about the values from the evaluation (train rmse | train rmse_pcutoff | train mAP | train mAR | test rmse | test rmse_pcutoff | test mAP | test mAR). Upon a quick search I didn't find this in the documentation.

  26. n-poulsen commented on Jan 30, 2025

    @n-poulsen
    Contributor

    @frikyng The CPU can indeed become a bottleneck. During training, as we're dealing with images, increasing the number of dataloader_workers can improve GPU utilisation and training speed; so when increasing the batch size, it's also a good idea to increase the number of workers (each worker is in a different thread, so good values to try out are 1, 2, 4, 8, 12 but above that you likely won't get any more speed-up - more info about this here).

    However, it isn't straightforward to do this during video analysis, as the video needs to be decoded sequentially - so no workers can be used there. Also note that the resolution of your video has a huge impact on FPS, due to the model needing to run on large images but also due to data loading.

    When it comes to the results that you should target, there isn't really anything specific; this is because results will be specific to your data. You can't hope for the same performance in a complicated video where many mice overlap than in a video where a single mouse is in an openfield. In the same way, if your image is 2000 pixels by 2000 pixels, an RMSE (root mean square error, or pixel error) of 5px will have a different meaning than if your image is 128 pixels by 128 pixels. It's a good idea to look at the predictions output by the model on a video and make sure they look good; video predictions should also be smooth and not jitter between frames.

    A good note from the docs would be:

    What (numerically) comprises an acceptable MAE depends on many factors (including the size of the tracked body parts, the labeling variability, etc.). Note that the test error can also be larger than the training error due to human variability (in labeling, see Figure 2 in Mathis et al, Nature Neuroscience 2018).

    If we look at figure 2, the human variability sits just below 3 pixels, and the model error can actually go below that value; with the examples you shared, I'd expect the RMSE to go below 10 pixels (and likely below 5). I'd also expect your mAP to be above 90, but for single animal datasets RMSE is a good metric to look at.

    The other metrics, mAP and mAR, are more useful for multi-animal dataset. There's detailed information on computing mAP for keypoints, but it's similar to computing mAP for bounding boxes for which there are more "visual" resources to understand the metric.

  27. surjeets commented on Jan 30, 2025

    @surjeets

    @frikyng here is the config file adding it as txt and I removed path information that you can add that is relevant to you project
    config.txt

  28. frikyng commented on Jan 30, 2025

    @frikyng

    Ok nice. This is some really good info. Time to get to training. Thanks very much @n-poulsen!
    Also thanks for the file @surjeets!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions