{"slug": "pytorch-permute-vs-transpose-what-s-the-difference-and-the-reshape-bug-that-your", "title": "PyTorch `permute` vs `transpose`: What's the Difference (and the `reshape` Bug That Scrambles Your Images)", "summary": "A developer explains the critical difference between PyTorch's permute, transpose, and reshape operations, warning that reshape can silently scramble image data when converting from (N, H, W, C) to (N, C, H, W) layout. The post demonstrates that while permute and transpose return views with reordered strides, reshape reinterprets flat memory and can produce the correct shape but incorrect values, leading to corrupted images.", "body_md": "You loaded an image, got a tensor shaped `(batch, height, width, channels)`\n\n, and your convolution wants `(batch, channels, height, width)`\n\n. Stack Overflow says `permute`\n\n. Someone else says `transpose`\n\n. And `reshape(2, 3, 28, 28)`\n\ngives you the right shape too — so why is everyone making this complicated?\n\nBecause two of those three are the same tool, and the third one silently destroys your data.\n\n`transpose(dim0, dim1)`\n\nswaps **exactly two** dimensions. `permute(...)`\n\nreorders **all** of them in one call, and you must list every dimension. `transpose`\n\nis a special case of `permute`\n\n. Both return a **view** — no data is copied, only the strides change — which also means both leave you with a non-contiguous tensor.\n\n`reshape`\n\nis not in this family at all. It reinterprets the flat memory under a new shape without moving anything, so it can produce the shape you asked for while completely scrambling what the numbers mean.\n\n``` python\nimport torch\n\nt = torch.arange(24).reshape(2, 3, 4)\n\nprint(t.transpose(0, 1).shape)     # torch.Size([3, 2, 4])  — swapped dims 0 and 1\nprint(t.permute(2, 0, 1).shape)    # torch.Size([4, 2, 3])  — full reorder\n```\n\n`transpose`\n\n— swap two axes\n`transpose(dim0, dim1)`\n\ntakes two dimension indices and swaps them. Everything else stays put.\n\n```\nt = torch.arange(24).reshape(2, 3, 4)\n\nprint(t.shape)                  # torch.Size([2, 3, 4])\nprint(t.transpose(0, 1).shape)  # torch.Size([3, 2, 4])\nprint(t.transpose(1, 2).shape)  # torch.Size([2, 4, 3])\n```\n\nThe order of the two arguments doesn't matter — `t.transpose(0, 1)`\n\nand `t.transpose(1, 0)`\n\nare the same thing. A swap is a swap.\n\nOn a 2-D tensor this is the matrix transpose you already know, and `.T`\n\nis the shorthand:\n\n```\nm = torch.arange(6).reshape(2, 3)\nprint(m.T.shape)                # torch.Size([3, 2])\nprint(m.transpose(0, 1).shape)  # torch.Size([3, 2])  — identical\n```\n\n**One caution on .T:** on tensors with more than two dimensions,\n\n`.T`\n\nreverses `.mT`\n\n```\nt = torch.arange(24).reshape(2, 3, 4)\nprint(t.mT.shape)   # torch.Size([2, 4, 3]) — swaps the last two dims, batch untouched\n```\n\nReserve plain `.T`\n\nfor 2-D matrices. On anything higher, say what you mean with `permute`\n\nor `.mT`\n\n.\n\n`permute`\n\n— state the whole new order\n`permute`\n\ndoesn't swap; it *rewrites the dimension order in full*. You pass the old index of each dimension in the position you want it to end up.\n\n```\nt = torch.arange(24).reshape(2, 3, 4)\nprint(t.permute(2, 0, 1).shape)   # torch.Size([4, 2, 3])\n```\n\nRead `permute(2, 0, 1)`\n\nas: **\"new dim 0 is old dim 2, new dim 1 is old dim 0, new dim 2 is old dim 1.\"** Not \"move dim 2 somewhere\" — you are writing out the destination order, left to right.\n\nTwo consequences worth internalising:\n\n`RuntimeError: number of dims don't match in permute`\n\n.`permute`\n\n:\n\n```\nt = torch.arange(24).reshape(2, 3, 4)\n\nvia_permute    = t.permute(1, 2, 0)                    # torch.Size([3, 4, 2])\nvia_transposes = t.transpose(0, 1).transpose(1, 2)     # torch.Size([3, 4, 2])\n\nprint(torch.equal(via_permute, via_transposes))   # True\n```\n\nSame result. The `permute`\n\nversion says the destination shape out loud; the chained version makes the reader simulate two swaps in their head. Prefer `permute`\n\nfor anything beyond a single swap.\n\n`permute`\n\nis not `reshape`\n\nHere is the bug this article exists for. You have a batch of images in `(N, H, W, C)`\n\n— the layout you get from OpenCV, PIL, TensorFlow, and most image files — and PyTorch convolutions need `(N, C, H, W)`\n\n.\n\nBoth of these produce a tensor of the right shape:\n\n```\nimg = torch.arange(1 * 2 * 2 * 3).reshape(1, 2, 2, 3)   # N=1, H=2, W=2, C=3\n\nprint(img.permute(0, 3, 1, 2).shape)   # torch.Size([1, 3, 2, 2])  ✅\nprint(img.reshape(1, 3, 2, 2).shape)   # torch.Size([1, 3, 2, 2])  ⚠️ same shape!\n```\n\nSame shape. No error. No warning. Now look at what's actually inside the first channel:\n\n```\nprint(img.permute(0, 3, 1, 2)[0, 0])\n# tensor([[0, 3],\n#         [6, 9]])            ← the red value of each of the 4 pixels ✅\n\nprint(img.reshape(1, 3, 2, 2)[0, 0])\n# tensor([[0, 1],\n#         [2, 3]])            ← pixel 0's R, G, B and then pixel 1's R ❌\n```\n\nThe `permute`\n\nversion collected the red channel: pixels are stored as `(R,G,B)(R,G,B)…`\n\n, so the reds are elements 0, 3, 6, 9. That's a real red channel.\n\nThe `reshape`\n\nversion just took the first four numbers in memory and called them \"channel 0\" — that's one whole pixel plus a third of the next one. Your \"red channel\" is now a mixture of red, green and blue from different pixels. The tensor is the right shape, the model trains, the loss goes down a little, and the accuracy is quietly terrible. Nothing on screen ever tells you.\n\nThe rule:`permute`\n\nmovesdimensions.`reshape`\n\nre-cuts thesame flat sequence of numbersinto new brackets. If you want to change what an axismeans, you need`permute`\n\n— always.\n\nIf you want the full picture on how `reshape`\n\nre-cuts memory, that's covered in [Reshape vs View in PyTorch](https://dev.to/pytorchfromgroundup/reshape-vs-view-in-pytorch-whats-the-difference-and-when-view-breaks-4a9o).\n\n**Images — channels-last to channels-first:**\n\n```\nimg = torch.randn(2, 28, 28, 3)          # N, H, W, C  (from PIL / OpenCV)\nx = img.permute(0, 3, 1, 2)              # N, C, H, W  (what nn.Conv2d wants)\nprint(x.shape)                           # torch.Size([2, 3, 28, 28])\n```\n\n**Attention — splitting into heads.** This is the one place where `reshape`\n\nand `permute`\n\ncorrectly appear back-to-back, and seeing why makes the distinction click:\n\n```\nB, S, E, H = 2, 5, 8, 2                  # batch, seq_len, embed_dim, heads\n\nx = torch.randn(B, S, E)                 # torch.Size([2, 5, 8])\nx = x.reshape(B, S, H, E // H)           # torch.Size([2, 5, 2, 4])  — split, don't move\nx = x.permute(0, 2, 1, 3)                # torch.Size([2, 2, 5, 4])  — move heads forward\n```\n\nThe `reshape`\n\nis legitimate here because it only *splits* the last axis — the 8 embedding values were already laid out contiguously, so cutting them into 2 groups of 4 doesn't reorder anything. The `permute`\n\nthen genuinely moves the head axis in front of the sequence axis. Splitting an axis is `reshape`\n\nwork; moving an axis is `permute`\n\nwork.\n\n`transpose`\n\nand `permute`\n\nnever touch the underlying data. They change the tensor's **strides** — the step size PyTorch takes through memory for each dimension:\n\n```\na = torch.arange(6).reshape(2, 3)\nprint(a.stride(), a.is_contiguous())            # (3, 1) True\n\nb = a.permute(1, 0)\nprint(b.shape, b.stride(), b.is_contiguous())   # torch.Size([3, 2]) (1, 3) False\n```\n\nThat's why they're free. It's also why the very next `.view()`\n\nyou call will blow up:\n\n```\nb.view(6)\n# RuntimeError: view size is not compatible with input tensor's size and stride\n# (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.\n```\n\nTwo fixes, and the choice matters:\n\n```\nb.reshape(6)                # works — copies quietly when it has to\nb.contiguous().view(6)      # works — reorders memory first, then views\n```\n\nUse `.reshape()`\n\nby default. Reach for an explicit `.contiguous()`\n\nwhen you're about to do many operations on the permuted tensor and want the memory laid out well once, up front, rather than copied repeatedly.\n\n`reshape`\n\nto convert NHWC → NCHW.`permute(0, 3, 1, 2)`\n\n.`permute(2, 0, 1)`\n\nas instructions to move things.`args[i]`\n\n. Say it out loud before you trust it.`permute`\n\nneeds all of them → `RuntimeError: number of dims don't match in permute`\n\n.`.T`\n\non 3-D+ tensors.`.mT`\n\nfor a batch of matrices, or `permute`\n\nto say it exactly.`.view()`\n\nright after a permute.`.reshape()`\n\nor `.contiguous().view()`\n\n.`print(x.stride())`\n\nnext to `print(x.shape)`\n\nwhen a shape bug won't make sense — the strides usually tell you the real story.`transpose(a, b)`\n\nswaps two dimensions; `permute(...)`\n\nrewrites the whole dimension order and needs every index listed. They do the same kind of work, and `permute`\n\nis the one to reach for whenever more than one swap is involved. Both are free view operations that leave the tensor non-contiguous, so the next `.view()`\n\nwill error — use `.reshape()`\n\n.\n\nAnd the part that costs people a weekend: ** reshape is not a reordering tool.** It can hand you a correctly-shaped tensor full of scrambled values, with nothing on screen to warn you. When an axis needs to\n\n**More in this series:** [Reshape vs View](https://dev.to/pytorchfromgroundup/reshape-vs-view-in-pytorch-whats-the-difference-and-when-view-breaks-4a9o) · [Broadcasting Explained](https://dev.to/pytorchfromgroundup/pytorch-broadcasting-explained-the-3-rules-and-the-silent-bug-that-bites-everyone-3606) · [What unsqueeze Does](https://dev.to/pytorchfromgroundup/what-does-unsqueeze-do-in-pytorch-and-why-your-model-keeps-asking-for-it-181a) ·\n\n`keepdim`\n\nDoes**A question for you:** what's the shape bug that cost you the most time? I'm collecting the ones that hit hardest — drop it in the comments and I'll write up the fix.\n\nThis is one idea from my book *PyTorch From Ground Up*, which builds everything from tensors upward so nothing stays vague. If it helped, you can grab the [free PyTorch tensor cheat-sheet here](https://payhip.com/b/7ukxh), run every example from the book in the [companion notebooks on GitHub](https://github.com/pytorch-from-ground-up/book_code), get the [digital edition on Leanpub](https://leanpub.com/pytorchfromgroundup), or find the [full paperback on Amazon here](https://www.amazon.com/dp/B0H8WMCV33).", "url": "https://wpnews.pro/news/pytorch-permute-vs-transpose-what-s-the-difference-and-the-reshape-bug-that-your", "canonical_source": "https://dev.to/pytorchfromgroundup/pytorch-permute-vs-transpose-whats-the-difference-and-the-reshape-bug-that-scrambles-your-7ke", "published_at": "2026-08-02 18:23:12+00:00", "updated_at": "2026-08-02 18:48:02.590238+00:00", "lang": "en", "topics": ["machine-learning", "developer-tools"], "entities": ["PyTorch"], "alternates": {"html": "https://wpnews.pro/news/pytorch-permute-vs-transpose-what-s-the-difference-and-the-reshape-bug-that-your", "markdown": "https://wpnews.pro/news/pytorch-permute-vs-transpose-what-s-the-difference-and-the-reshape-bug-that-your.md", "text": "https://wpnews.pro/news/pytorch-permute-vs-transpose-what-s-the-difference-and-the-reshape-bug-that-your.txt", "jsonld": "https://wpnews.pro/news/pytorch-permute-vs-transpose-what-s-the-difference-and-the-reshape-bug-that-your.jsonld"}}