semantic-segmentation-pytorch icon indicating copy to clipboard operation
semantic-segmentation-pytorch copied to clipboard

When trying to export to ONNX, export fails on adaptive_avg_pool2d

Open pranay731 opened this issue 5 years ago • 2 comments

I am trying to convert the models to onnx but the export fails with error

UserWarning: ONNX export failed on adaptive_avg_pool2d because output size that are not factor of input size not supported warnings.warn("ONNX export failed on " + op + " because " + msg + " not supported")

I tried exporting with ONNX_ATEN_FALLBACK and opset version 9 as well as 11, but same error occurs.

pranay731 avatar Jul 23 '20 07:07 pranay731

hello, I'm doing some work in exporting pth to onnx, can you share your scripts with me? Thank you very much

WuChao-2024 avatar Jul 17 '24 16:07 WuChao-2024

Hello is the issue solved? , how to convert ?

Md-Sayeed-Khan avatar Sep 17 '24 04:09 Md-Sayeed-Khan

In the past, I implemented a custom AdaptiveAvgPool2d module to get around this issue for a different model. Try replacing the three occurrences of nn.AdaptiveAvgPool2d in models.py with MyAdaptiveAvgPool2d. Maybe it works here as well.

import math
import torch
import torch.nn as nn

class MyAdaptiveAvgPool2d(nn.Module):
    def __init__(self, output_size):
        super().__init__()
        self.output_size = output_size

    def forward(self, batch):
        size = self.output_size
        n, c, h, w = batch.shape
        output = torch.zeros((n, c, size, size), device=batch.device)
        for y in range(size):
            for x in range(size):
                x0 = math.floor(x * w / size)
                y0 = math.floor(y * h / size)
                x1 = math.ceil((x + 1) * w / size)
                y1 = math.ceil((y + 1) * h / size)
                output[:, :, y, x] = batch[:, :, y0:y1, x0:x1].mean(dim=(2, 3))
        return output

99991 avatar Sep 04 '25 12:09 99991