How to Fix "Cannot Broadcast Tensors" in PyTorch

Broadcasting requires dimensions to match from the right. Use .unsqueeze() to add dimensions. Example: (3,4) + (4,) works, but (3,4) + (3,) fails because the rightmost dimensions 4 and 3 don't match.

Broadcasting Rules

Two dimensions are compatible when:

  1. They are equal, or
  2. One of them is 1

Dimensions are compared from right to left:

# Works: rightmost dims match
(3, 4) + (4,)   -> (3, 4)  ✓ 4==4
(3, 4) + (1, 4)  -> (3, 4)  ✓ 4==4, 1 broadcasts to 3
(2, 3, 4) + (4,)  -> (2, 3, 4) ✓ 4==4

# Fails: rightmost dims don't match
(3, 4) + (3,)   -> ERROR   ✗ 4!=3
(2, 3) + (2,)   -> ERROR   ✗ 3!=2

Fix, Use unsqueeze()

a = torch.randn(3, 4)  # shape (3, 4)
b = torch.randn(3)    # shape (3,)

# a + b # ERROR: (3,4) + (3,) — 4 != 3

# Fix: add a dimension to make (3,) -> (3, 1)
b = b.unsqueeze(-1)    # shape (3, 1)
result = a + b       # (3, 4) + (3, 1) -> (3, 4) ✓

Common Patterns

# Add bias per channel to image: (batch, C, H, W) + (C,)
bias = torch.randn(64)           # (64,)
bias = bias.unsqueeze(0).unsqueeze(-1).unsqueeze(-1) # (1, 64, 1, 1)
# or more concisely:
bias = bias.view(1, -1, 1, 1)       # (1, 64, 1, 1)
output = features + bias          # broadcasts ✓

# Scale per sample: (batch, features) * (batch,)
weights = torch.randn(32)         # (32,)
weights = weights.unsqueeze(-1)      # (32, 1)
result = data * weights           # (32, 128) * (32, 1) -> (32, 128) ✓
Try the Broadcast Error Solver

TENSOR PREFLIGHT · DOWNLOADABLE PYTORCH TOOLKIT

Take the next step in your own PyTorch model.

Trace a local forward pass, inspect tensor shapes in an HTML report, and turn a repair into a regression check. Includes eight broken-and-fixed workflows, source code and setup instructions.

Is this toolkit right for my problem?

Use the free calculator for a layer formula or a quick shape check.

Consider Tensor Preflight when you have a local PyTorch model and want a forward-pass report plus repeatable checks. Python 3.9+ and PyTorch 2.8+ are required. It does not run your model in this website or automatically repair it.

Open the sample report before buying to check the output format.

Python 3.9+ · PyTorch 2.8+ · Runs locally

Get Tensor Preflight — $29 One-time payment · ZIP download See a sample report
By the same builder: GitHub, theluckystrike BeLikeNative, Grammar AI EarlyThunder, Dev Blog Bug Bounty Reality Zovo, AI Dev Tools