Skip to content

Scale the right output channel when fusing batch_norm / scale into a grouped conv_transpose - #2938

Open
chaitanya0305 wants to merge 1 commit into
apple:mainfrom
chaitanya0305:fix/fuse-conv-grouped-deconv-channel-order
Open

chaitanya0305 wants to merge 1 commit into
apple:mainfrom
chaitanya0305:fix/fuse-conv-grouped-deconv-channel-order

Conversation

@chaitanya0305

Copy link
Copy Markdown

common::fuse_conv_batchnorm and common::fuse_conv_scale apply the per-channel factor to the wrong output channels of a grouped conv_transpose (groups > 1 and Cout / groups > 1). Both passes are in the default pipeline. As a result, a torch ConvTranspose{1,2,3}d(groups=g) followed by BatchNorm, or by a per-channel mul/div, converts without any warning to a model with wrong outputs. Depthwise transposed convs (Cout / groups == 1) and groups == 1 are not affected. Neither is regular conv.

Repro (coremltools main, macOS, CPU_ONLY, FLOAT32)

import numpy as np, torch, torch.nn as nn, coremltools as ct

torch.manual_seed(0)
net = nn.Sequential(nn.ConvTranspose1d(8, 8, 4, stride=2, padding=1, groups=2), nn.BatchNorm1d(8)).eval()
net[1].running_mean.normal_(); net[1].running_var.uniform_(0.5, 2.0); net[1].weight.data.normal_()
x = torch.randn(1, 8, 16)
with torch.no_grad():
    ref = net(x).numpy()
ml = ct.convert(torch.jit.trace(net, x), inputs=[ct.TensorType(name="x", shape=x.shape)],
                compute_precision=ct.precision.FLOAT32, compute_units=ct.ComputeUnit.CPU_ONLY)
out = list(ml.predict({"x": x.numpy()}).values())[0]
print("max abs diff:", np.abs(out - ref).max(), "max |ref|:", np.abs(ref).max())
main:        max abs diff: 1.698     max |ref|: 1.697
this branch: max abs diff: 1.19e-07  max |ref|: 1.697

The conversion without BN is correct. The error comes from the fusion.

Root cause

A conv_transpose weight has shape [Cin, Cout / groups, *D_in]. Output channel g * (Cout / groups) + j reads weight[g * Cin/groups : (g + 1) * Cin/groups, j].

Both passes transpose the weight to [Cout / groups, Cin, *D_in], reshape it to [Cout, Cin / groups, *D_in] and scale row c by scale[c]. After that reshape, row r holds output channel (r % groups) * (Cout / groups) + r // groups, not channel r. So whenever groups > 1 and Cout / groups > 1, kernels get another channel's factor. The bias update is indexed by output channel, so it is correct. The result is that kernels and biases no longer agree.

Fix

  • Add _scale_conv_weight_per_output_channel(). For conv it broadcasts the scale over axis 0. For conv_transpose it reshapes the weight to [groups, Cin / groups, Cout / groups, *D_in] and broadcasts scale.reshape(groups, 1, Cout / groups, ...).
  • Use the helper in both fuse_conv_batchnorm and fuse_conv_scale. This replaces the per-channel Python loops and the transpose/reshape round trip. The BN bias update is now vectorized with the same formula.
  • Remove locals that are no longer used (Cin, deconv_weight_transpose_axes, is_conv_1d). This also drops the hard-coded [1, 0, 2, 3] transpose in fuse_conv_scale.

Tests

The existing test_conv_transpose cases for both passes only check output shapes, so they pass on main. New tests:

  • TestConvBatchNormFusion::test_grouped_conv_numerics: rank 3/4/5, groups 2/3, conv and conv_transpose.
  • TestConvScaleFusion::test_grouped_conv_numerics: rank 3/4, groups 2/3, conv and conv_transpose, mul and real_div.

Both run the fused program and compare the prediction with torch (conv* / conv_transpose* + batch_norm or scale). On main, all 14 conv_transpose cases fail and all conv cases pass. With this branch, all pass.

pytest coremltools/converters/mil/mil/passes/tests/test_passes.py -k "TestConvBatchNormFusion or TestConvScaleFusion or TestConvBiasFusion"
605 passed

The rest of test_passes.py gives the same results as on main. Locally, TestReplaceStackReshape (numpy reshape(newshape=)) and TestRandomizeWeights (needs torchvision) fail on main as well.

fuse_conv_batchnorm and fuse_conv_scale fold a per-channel factor into
the conv weight. For conv_transpose the weight is [Cin, Cout / groups,
*D_in]; both passes transposed it to [Cout / groups, Cin, *D_in] and
reshaped to [Cout, Cin / groups, *D_in], assuming row c of the result
is output channel c. With groups > 1 and Cout / groups > 1, row
j * groups + g holds output channel g * (Cout / groups) + j, so the
factors were applied to the wrong kernels. A torch ConvTranspose1d
(groups=2) followed by BatchNorm1d converted to a model whose output
differs from torch by as much as the output itself. Depthwise and
groups=1 layers were not affected.

Move the per-channel weight scaling into one helper that reshapes the
transposed-conv weight to [groups, Cin / groups, Cout / groups, *D_in]
and broadcasts the factors per group, and use it in both passes.

The existing tests only checked output shapes. Add prediction tests
against torch for grouped conv and conv_transpose in both passes.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant