pytorch - 💡(How to fix) Fix [MPS] Conv3d backward fails with "required rank 4 tensor to use channels_last format" when combined with view/permute/Linear [1 comments, 2 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
pytorch/pytorch#178222Fetched 2026-04-08 01:21:11
View on GitHub
Comments
1
Participants
2
Timeline
111
Reactions
0
Participants
Assignees
Timeline (top)
mentioned ×48subscribed ×48referenced ×6labeled ×5

Error Message

  RuntimeError: required rank 4 tensor to use channels_last format

The error occurs during backward(), not during the forward pass.

Key observations

  • B=1 (BT=28): works. B≥2 (BT≥56): fails.
  • Adding .contiguous() before any layer (Linear, einsum, conv2) does not fix it.
  • All tensors are contiguous and not channels_last_3d during the forward pass.
  • Each operation in isolation works fine — the bug only manifests in the combined backward graph.
  • PYTORCH_ENABLE_MPS_FALLBACK=1 does not help.
  • PYTORCH_MPS_PREFER_METAL=1 does not help (and causes additional Metal command buffer errors).
  • Also reproduced on PyTorch nightly 2.12.0.dev20260323 — same failure.

Fix Action

Fix / Workaround

No .contiguous() workaround fixes it — the issue is in autograd's internal gradient tensor layout management during the backward pass, not in forward-pass tensor layouts.

Code Example

import torch
  import torch.nn as nn

  device = torch.device('mps')
  B, T, C, r = 2, 28, 64, 16
  BT = B * T  # 56 — fails. Set B=1 (BT=28) and it works.

  conv1 = nn.Conv3d(C, C, 3, padding=1).to(device)
  proj  = nn.Linear(C, C).to(device)
  conv2 = nn.Conv3d(C, C, 3, padding=1).to(device)

  x = torch.randn(BT, C, r, r, r, device=device)
  x = conv1(x)                                          # Conv3d forward
  x = x.view(B, T, C, -1).permute(0, 3, 2, 1)          # (BT,C,r,r,r)  (B,, C, T)
  x = torch.einsum('BNCT -> BNTC', x)                   # permute last dims
  x = proj(x)                                            # nn.Linear
  x = torch.einsum('BNTC -> BNCT', x)                   # permute back
  x = x.permute(0, 3, 2, 1).reshape(BT, C, r, r, r)    # (B,, C, T)  (BT,C,r,r,r)
  x = conv2(x)                                           # Conv3d forward
  x.sum().backward()  # RuntimeError: required rank 4 tensor to use channels_last format

---

RuntimeError: required rank 4 tensor to use channels_last format
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

The backward pass crashes on the MPS backend when a computation graph contains Conv3d layers connected through view/permute/einsum/Linear operations. The error is batch-size dependent: it works when the Conv3d batch dimension is 28 but fails at 56+.

No .contiguous() workaround fixes it — the issue is in autograd's internal gradient tensor layout management during the backward pass, not in forward-pass tensor layouts.

Minimal reproducer

import torch
import torch.nn as nn

device = torch.device('mps')
B, T, C, r = 2, 28, 64, 16
BT = B * T  # 56 — fails. Set B=1 (BT=28) and it works.

conv1 = nn.Conv3d(C, C, 3, padding=1).to(device)
proj  = nn.Linear(C, C).to(device)
conv2 = nn.Conv3d(C, C, 3, padding=1).to(device)

x = torch.randn(BT, C, r, r, r, device=device)
x = conv1(x)                                          # Conv3d forward
x = x.view(B, T, C, -1).permute(0, 3, 2, 1)          # (BT,C,r,r,r) → (B, r³, C, T)
x = torch.einsum('BNCT -> BNTC', x)                   # permute last dims
x = proj(x)                                            # nn.Linear
x = torch.einsum('BNTC -> BNCT', x)                   # permute back
x = x.permute(0, 3, 2, 1).reshape(BT, C, r, r, r)    # (B, r³, C, T) → (BT,C,r,r,r)
x = conv2(x)                                           # Conv3d forward
x.sum().backward()  # RuntimeError: required rank 4 tensor to use channels_last format

Error message

RuntimeError: required rank 4 tensor to use channels_last format

The error occurs during backward(), not during the forward pass.

Key observations

  • B=1 (BT=28): works. B≥2 (BT≥56): fails.
  • Adding .contiguous() before any layer (Linear, einsum, conv2) does not fix it.
  • All tensors are contiguous and not channels_last_3d during the forward pass.
  • Each operation in isolation works fine — the bug only manifests in the combined backward graph.
  • PYTORCH_ENABLE_MPS_FALLBACK=1 does not help.
  • PYTORCH_MPS_PREFER_METAL=1 does not help (and causes additional Metal command buffer errors).
  • Also reproduced on PyTorch nightly 2.12.0.dev20260323 — same failure.

Versions

PyTorch version: 2.11.0 Is debug build: False CUDA used to build PyTorch: None ROCM used to build PyTorch: N/A

OS: macOS 26.3.1 (arm64) GCC version: Could not collect Clang version: 17.0.0 (clang-1700.6.4.2) CMake version: version 4.1.1 Libc version: N/A

Python version: 3.11.15 | packaged by conda-forge | (main, Mar 5 2026, 16:59:26) [Clang 19.1.7 ] (64-bit runtime) Python platform: macOS-26.3.1-arm64-arm-64bit Is CUDA available: False CUDA runtime version: No CUDA GPU models and configuration: No CUDA

CPU: Apple M2 Max

[pip3] torch==2.11.0 [pip3] torchvision==0.26.0

cc @ezyang @albanD @gqchen @nikitaved @soulitzer @Varal7 @bobrenjc93 @mruberry @jbschlosser @walterddr @mikaylagawarecki @kulinseth @malfet @DenisVieriu97 @jhavukainen @aditvenk

extent analysis

Fix Plan

To fix the issue, we need to ensure that the tensor layout is compatible with the channels_last format required by the mps backend. We can achieve this by adding a to method call with the memory_format argument set to torch.channels_last_3d after the permute and reshape operations.

Here are the concrete steps:

  • Add to method call with memory_format argument after permute and reshape operations:
x = x.view(B, T, C, -1).permute(0, 3, 2, 1).to(memory_format=torch.channels_last_3d)
x = torch.einsum('BNCT -> BNTC', x)
x = proj(x)
x = torch.einsum('BNTC -> BNCT', x)
x = x.permute(0, 3, 2, 1).reshape(BT, C, r, r, r).to(memory_format=torch.channels_last_3d)
  • Verify that the fix works by running the modified code and checking that the backward pass completes without errors.

Verification

To verify that the fix worked, run the modified code and check that the backward pass completes without errors. You can do this by adding a try-except block around the backward call and checking that no exception is raised:

try:
    x.sum().backward()
    print("Backward pass completed successfully")
except RuntimeError as e:
    print(f"Error: {e}")

If the fix is successful, the backward pass should complete without errors, and the message "Backward pass completed successfully" should be printed.

Extra Tips

  • Make sure to use the to method with the memory_format argument to ensure that the tensor layout is compatible with the channels_last format required by the mps backend.
  • If you encounter similar issues in the future, try adding to method calls with the memory_format argument to ensure that the tensor layout is compatible with the required format.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING