data-gen-bpu/scripts/test_mmseg_static_pool.py

32 lines
1.3 KiB
Python

"""Non-divisible pooling bins must match PyTorch after actual ONNX export."""
import io
import unittest
import numpy as np
import onnxruntime as ort
import torch
from harness.adapters.mmseg_common import lower_static_pools
class StaticPooling(unittest.TestCase):
def test_rectangular_bins_keep_the_official_mean(self):
torch.manual_seed(17)
for shape, output in (((5, 7), 3), ((64, 128), 6), ((8, 12), 2)):
with self.subTest(shape=shape, output=output):
x = torch.randn(1, 3, *shape)
model = torch.nn.Sequential(torch.nn.AdaptiveAvgPool2d(output)).eval()
expected = model(x).numpy()
lower_static_pools(model)
np.testing.assert_array_equal(model(x).numpy(), expected)
stream = io.BytesIO()
torch.onnx.export(model, x, stream, opset_version=11, input_names=['image'])
options = ort.SessionOptions(); options.intra_op_num_threads = 2
session = ort.InferenceSession(stream.getvalue(), sess_options=options, providers=['CPUExecutionProvider'])
actual = session.run(None, {'image': x.numpy()})[0]
np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-6)
if __name__ == '__main__':
unittest.main()