Skip to content

Fix torch pad: (before, after) pairs were swapped for asymmetric pad_width - #36

Merged
jcmgray merged 1 commit into
jcmgray:mainfrom
Ryo-wtnb11:fix-torch-pad-pair-order
Aug 16, 2026
Merged

Fix torch pad: (before, after) pairs were swapped for asymmetric pad_width#36
jcmgray merged 1 commit into
jcmgray:mainfrom
Ryo-wtnb11:fix-torch-pad-pair-order

Conversation

@Ryo-wtnb11

Copy link
Copy Markdown
Contributor

torch_pad flattened pad_width and then reversed the whole flat tuple, which reverses each (before, after) pair as well as the axis order — so on the torch backend padding placed before an axis ended up after it, and vice versa. Symmetric pads are unaffected, which is presumably why it went unnoticed.

The fix is to reverse the axis order before flattening:

pad = tuple(itertools.chain.from_iterable(pad_width))[::-1]        # wrong
pad = tuple(itertools.chain.from_iterable(reversed(pad_width)))    # right

torch's flat format is (before_last, after_last, before_secondlast, ...), i.e. axes reversed but each pair in order. The single-tuple broadcast branch (len(pad) == 2 -> pad * ndim) also becomes correct for an asymmetric ((a, b),), which was previously swapped too.

test_pad only checked the output shape and sum, both of which are invariant under the swap. It now also compares against np.pad and has an asymmetric pad_width case; that test fails on the torch backend before this change and passes after.

Fixes #35

@jcmgray

jcmgray commented Aug 16, 2026

Copy link
Copy Markdown
Owner

Looks good thanks!

@jcmgray
jcmgray merged commit 582dcbd into jcmgray:main Aug 16, 2026
10 checks passed
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.

torch backend: do("pad", ...) swaps (before, after) for asymmetric pad_width

2 participants