Skip to content

fix: use correct in/out channels in default Conv1d and Conv2d mapping - #56

Open
AxelNoun wants to merge 1 commit into
neuromorphs:mainfrom
AxelNoun:fix/conv-default-map-channels
Open

AxelNoun wants to merge 1 commit into
neuromorphs:mainfrom
AxelNoun:fix/conv-default-map-channels

Conversation

@AxelNoun

Copy link
Copy Markdown

Problem

_default_map_conv1d and _default_map_conv2d pass the weight dimensions to
torch.nn.Conv1d / Conv2d in the wrong order: C_out is used as
in_channels and C_in / groups as out_channels.

With groups=1 the forward pass is still correct, because the weight is
overwritten afterwards, but in_channels and out_channels of the module are
swapped. With groups > 1 the constructor can fail, so a valid depthwise NIR
node cannot be imported with DEFAULT_MAP:

import nir, numpy as np
from nirtorch import nir_interpreter

w = np.ones((4, 1, 3), dtype=np.float32)  # depthwise, 4 channels
node = nir.Conv1d(None, w, 1, 0, 1, 4, np.zeros(4, dtype=np.float32))
nir_interpreter._map_nir_node_to_torch(node, nir_interpreter.DEFAULT_MAP)
# ValueError: out_channels must be divisible by groups

Fix

Use in_channels = weight.shape[1] * groups and out_channels = weight.shape[0],
which is the layout torch.nn.Conv1d / Conv2d use for their own weight.

Tests

  • test_map_conv1d_node and test_map_conv2d_node now check in_channels
    and out_channels.
  • New parametrized tests for depthwise, grouped and depthwise-multiplier
    convolutions compare the mapped module with torch.nn.functional.conv1d /
    conv2d.

Before the fix: 8 failed. After: 83 passed, 2 skipped on the full suite, on
Windows (Python 3.10 to 3.13) and Linux (Python 3.10 and 3.13), with nir 1.0.8
and torch CPU. ruff check passes.

Notes

The new tests use input_shape=None, so they do not depend on
neuromorphs/NIR#204.

The default mapping passed C_out as in_channels and C_in / groups as
out_channels. With groups=1 the forward pass stayed correct because the
weight is overwritten afterwards, but the module attributes were swapped.
With groups > 1 the constructor could raise "out_channels must be
divisible by groups", so a depthwise NIR node could not be imported.

Use in_channels = weight.shape[1] * groups and out_channels =
weight.shape[0], and add tests for depthwise and grouped convolutions.

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