ultralytics / yolov5

YOLOv5 🚀 in PyTorch > ONNX > CoreML > TFLite
https://docs.ultralytics.com
GNU Affero General Public License v3.0
50.39k stars 16.26k forks source link

Batch size set to one during model initialization #8722

Closed f180n4cc1 closed 2 years ago

f180n4cc1 commented 2 years ago

Search before asking

Question

Hello everybody.

I've encountered a problem during experimentation with Yolov5. I've have been tampering with adding SKNet like attention mechanism in Yolov5. The issue is that at one point in the attention module I need to use global average pool over the feature space and produce a feature vector that is (batch size, number of channels, 1, 1) that then needs to be batch normalized. When said model is initialized in train.py, an error occurs, since the batch size after model creation is set to 1. I've traced the problem to the init function of Model class in yolo.py, or more precisely to then block of if isinstance(m, Detect). In that block we have a call to self.forward method with dummy tensors from torch.zeros with shape (1, ch, s, s). If I change the batch size to anything other than 1 everything works, which makes sense since batch normalization needs to work on batch size that is greater then 1 during training, in order to calculate mean and variance. My question is then if this is a valid modification, or is there something that I'm missing?

Additional

No response

github-actions[bot] commented 2 years ago

👋 Hello @f180n4cc1, 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://ultralytics.com or email support@ultralytics.com.

Requirements

Python>=3.7.0 with all requirements.txt installed including PyTorch>=1.7. To get started:

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

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), validation (val.py), inference (detect.py) and export (export.py) on macOS, Windows, and Ubuntu every 24 hours and on every commit.

glenn-jocher commented 2 years ago

@f180n4cc1 batch normalization works at any batch size including batch size 1, i.e. see example below, so this is likely related to your custom modifications rather than anything in master. If you find any reproducible bugs in master please let us know though.

Screen Shot 2022-07-26 at 12 58 26 PM
f180n4cc1 commented 2 years ago

@glenn-jocher. Thanks for the quick reply. Batch normalization does work with batch size 1 on its own, but only if other dimensions are not 1. In my case I need to use global average pooling before batch normalization, that creates a tensor whose shape is (batch_size, num_channels, 1, 1), and if in that instance the batch size is 1, the procedure fails. The easiest way to reproduce it is to change Conv model's forward pass like in this code snippet `class Conv(nn.Module):

Standard convolution

def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):  # ch_in, ch_out, kernel, stride, padding, groups
    super().__init__()
    self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
    self.bn = nn.BatchNorm2d(c2)
    self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())

def forward(self, x):
    x = self.conv(x)
    x1 = torch.nn.AdaptiveAvgPool2d((1, 1))(x)
    x1 = self.bn(x1)
    x = torch.mul(x, x1)
    x = self.act(x)
    return self.act(self.bn(self.conv(x)))`

Now if you try to run train with yolov5s.yaml, it will fail in the same way as my custom implementation fails. edit; code pasting into snippet failed

glenn-jocher commented 2 years ago

@f180n4cc1 got it. If your custom architecture/ordering is causing errors then I'd revisit the design of your custom architecture.

f180n4cc1 commented 2 years ago

@glenn-jocher Thanks, will do.

github-actions[bot] commented 2 years ago

👋 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 ⭐!

glenn-jocher commented 11 months ago

@f180n4cc1 you're welcome! Good luck with your custom architecture, and feel free to reach out if you have any other questions.