ultralytics / yolov5

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

Why do my results differ using the same weights? #9304

Closed antopost closed 1 year ago

antopost commented 2 years ago

Search before asking

Question

I want to use YOLOv5 pre-trained layer weights as part of a multi-task network. For this I saved the state_dict, loaded my custom model and overwrote the object detection layers (see below). Simply calling model.load_state_dict does not work, since I named my model layers differently. For inference I'm using a custom detect module.

Problem: Although I use exactly the same weights and input, the results are very different (left are mine): output comparison

I compared some of the intermediate results from different layers and noticed that they drift apart the further the data move through the network. It seems like the error is due to rounding but both models and input are 32bit.

In my own implementation I defined my model like so (the other task heads have been omitted):

class YOLOPointMFull(nn.Module):
def __init__(self, inp_ch=3, nc=80, anchors=anchors):
    super(YOLOPointMFull, self).__init__()

    # CSPNet Backbone
    self.Conv1 = Conv(inp_ch, 48, 6, 2, 2)   # ch_in, ch_out, kernel, stride, padding, groups
    self.Conv2 = Conv(48, 96, 3, 2)
    self.Bottleneck1 = C3(96, 96, 2)    # ch_in, ch_out, number
    self.Conv3 = Conv(96, 192, 3, 2)
    self.Bottleneck2 = C3(192, 192, 4)
    self.Conv4 = Conv(192, 384, 3, 2)
    self.Bottleneck3 = C3(384, 384, 6)
    self.Conv5 = Conv(384, 768, 3, 2)
    self.Bottleneck4 = C3(768, 768, 2)
    self.SPPooling = SPPF(768, 768, 5)

    # Object Detector Head
    self.Conv6 = Conv(768, 384, 1, 1, 0)
    # ups, cat
    self.Bottleneck5 = C3(768, 384, 2)
    self.Conv7 = Conv(384, 192, 1, 1, 0)
    # ups, cat
    self.Bottleneck6 = C3(384, 192, 2)  # --> detect
    self.Conv8 = Conv(192, 192, 3, 2, 1)
    # cat
    self.Bottleneck7 = C3(384, 384, 2)  # --> detect
    self.Conv9 = Conv(384, 384, 3, 2, 1)
    # cat
    self.Bottleneck8 = C3(768, 768, 2)  # --> detect
    self.Detect = Detect(nc, anchors=anchors, ch=(192, 384, 768))

    self.ups = nn.Upsample(scale_factor=(2, 2), mode='nearest')

def forward(self, x):
    # Backbone
    x = self.Conv1(x)
    x = self.Conv2(x)   # check
    x = self.Bottleneck1(x)
    x = self.Conv3(x)
    xb = self.Bottleneck2(x)
    x = self.Conv4(xb)
    xc = self.Bottleneck3(x)
    x = self.Conv5(xc)
    x = self.Bottleneck4(x)
    x = self.SPPooling(x)

    # Object Detector Head
    xd = self.Conv6(x)
    x = self.ups(xd)
    x = torch.cat((x, xc), dim=1)
    x = self.Bottleneck5(x)
    xe = self.Conv7(x)
    x = self.ups(xe)
    x = torch.cat((x, xb), dim=1)
    xf = self.Bottleneck6(x)
    x = self.Conv8(xf)
    x = torch.cat((x, xe), dim=1)
    xg = self.Bottleneck7(x)
    x = self.Conv9(xg)
    x = torch.cat((x, xd), dim=1)
    x = self.Bottleneck8(x)
    x = self.Detect([xf, xg, x])

    return x

With this method I overwrote the weights of the network to work around the fact that both state_dicts have differently named keys:

yolo_statedict = torch.load('yolov5m.pt')

# load model with default anchors, input channels and classes
model = load_model('Model')

my_statedict = model.state_dict()

def load_pretrained(target, source):
    print(len(target), len(source))
    for i, (tk, sk) in enumerate(zip(target, source)):
        layer_target = tk.split('.')[-1]
        layer_source = sk.split('.')[-1]
        if layer_source == layer_target and source[sk].shape == target[tk].shape:
            target[tk] = source[sk]
        else:
            print(f'Failed to overwrite {tk}')
    return target

my_statedict = load_pretrained(my_statedict, yolo_statedict)

torch.save({"model_state_dict": my_statedict,}, 'my_statedict.pt')

The output seems to only begin to diverge after the first C3 module (see YOLOv5 architecture) or to be more exact, after (both of) the ConvBNSiLU layers of the C3 module. The mean absolute difference of the tensors when they first diverge is just 9.7185235e-05 which is small enough to be a rounding error. To double-check, I confirmed that the weights of the Conv layers of either implementation are exactly the same.

Additional

Here are some things that I have already checked / additional info:

github-actions[bot] commented 2 years ago

👋 Hello @antopost, 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

@antopost naturally I can't assist debugging your custom code, but I can provide a bit of advice: don't reinvent the wheel. If the official model works well, then I'd use that.

github-actions[bot] commented 1 year 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 ⭐!