PyTorch MSELoss Broadcasting: Fix [B, 1] vs [B] Targets
See how mismatched PyTorch MSELoss shapes create cross-row errors and can reverse a gradient. Fix [B, 1] vs [B] targets and try the free PTCA sample.
Give PyTorch MSELoss predictions and targets the same shape. For scalar regression with predictions shaped [B, 1] and one target per row shaped [B], use target.unsqueeze(-1) to make the target [B, 1]. If your training loop uses vectors, use pred.squeeze(-1) so both tensors are [B]. Without either fix, broadcasting can compare every prediction with every target, creating a [B, B] error matrix and training against the wrong loss.
Why the target size warning changes the loss
PyTorch aligns dimensions from the right. A target vector of shape [B] acts like a row with shape [1, B]. A prediction column of shape [B, 1] can expand across the columns, while the target row can expand down the rows. The result has one entry for each prediction and target pair. Only the diagonal pairs came from the same training row.
With the default mean reduction, all entries contribute to the returned scalar. A training loop can call backward and step successfully while optimizing that scalar. If predictions drift toward the batch mean, inspect the loss inputs before tuning the learning rate or blaming model capacity.
Source: PyTorch broadcasting semantics ↗
Work through three predictions before and after the fix
Say the predictions are 2, 5 and 8 for targets 1, 4 and 7 in that order. Each paired prediction misses by 1, so the intended mean squared error is 1. Look at the top-right cell in the broadcast result. The prediction 2 gets compared with target 7, contributing a squared error of 25 for a pair that does not belong together.
Switch to reduction="none" to see which errors are being averaged. The mismatched tensors yield nine errors that sum to 117, for a mean of 13. After inserting the target feature dimension, there are three squared errors of 1. This check shows exactly which calculation the warning points to.
import torch
import torch.nn.functional as F
pred = torch.tensor([[2.0], [5.0], [8.0]]) # [3, 1]
target = torch.tensor([1.0, 4.0, 7.0]) # [3]
# This call emits a shape warning.
wrong = F.mse_loss(pred, target, reduction="none")
print(wrong.tolist()) # [[1, 4, 25], [16, 1, 4], [49, 16, 1]]
print(wrong.mean().item()) # 13.0
target_column = target.unsqueeze(-1)
right = F.mse_loss(pred, target_column, reduction="none")
print(right.tolist()) # [[1], [1], [1]]
print(right.mean().item()) # 1.0How broadcasting can reverse a training update
The warning changes what the model learns. In the example above, the first prediction is 2 and its real target is 1. The correct MSE gradient for that prediction is +2/3, so gradient descent would decrease it. In the broadcast loss, that same prediction is compared to 1, 4 and 7. Its gradient is 2 × ((2 − 1) + (2 − 4) + (2 − 7)) / 9 = −4/3. That update would increase the first prediction and move it further from its own target.
The sign is easy to check by hand. With the right shapes, each scalar gradient is 2 × (prediction − its target) / B. In this particular [B, 1] against [B] case, the wrong objective gives 2 × (prediction − mean of all targets) / B. This describes gradients with respect to the prediction tensor. A model's parameter update still depends on how those predictions were computed.
For a PTCA decision question, suppose the target has shape [B], you need [B, 1] predictions for downstream code, and the last batch may have one row. Choose target.unsqueeze(-1). Averaging with a different reduction still includes cross-row pairs. Using pred.squeeze() can lose the only batch dimension. Repeating targets into a square matrix preserves the unintended comparisons.
p = pred.clone().requires_grad_()
bad_loss = F.mse_loss(p, target)
good_loss = F.mse_loss(p, target.unsqueeze(-1))
bad_grad, = torch.autograd.grad(bad_loss, p)
good_grad, = torch.autograd.grad(good_loss, p)
print([round(x, 3) for x in bad_grad[:, 0].tolist()])
# [-1.333, 0.667, 2.667]
print([round(x, 3) for x in good_grad[:, 0].tolist()])
# [0.667, 0.667, 0.667]
assert bad_grad[0, 0] < 0 < good_grad[0, 0]Choose a fix that also works with one example
Keep predictions in column form if the rest of your regression loop expects [B, 1]. Add a trailing dimension to the target. If downstream metrics expect [B], use pred.squeeze(-1) after verifying there is exactly one prediction per row. Plain pred.squeeze() can remove the batch axis when the final batch contains one row. Switching from mean to sum also leaves the unintended pairs in the computation.
Check the shapes before you call the loss. For a two-output regression head, every row needs two aligned target values. Adding a singleton dimension to a single target would hide that data contract error. The guard below is specifically for one scalar target per example. Use the same guard in training and validation if they share that contract.
def scalar_regression_loss(pred, target):
# Contract: predictions are [B, 1], targets are [B].
if pred.ndim != 2 or pred.shape[-1] != 1:
raise ValueError(f"Expected [B, 1] predictions, got {pred.shape}")
if target.ndim != 1 or target.shape[0] != pred.shape[0]:
raise ValueError(f"Expected one target per row, got {target.shape}")
return F.mse_loss(pred, target.unsqueeze(-1))
print(scalar_regression_loss(pred[:1], target[:1]).item()) # 1.0Test the same reasoning on a PTCA practice question
Before running a shape question, write down the two shapes, align them on the right, and count the errors that reduction will average. When the values look right row by row, ask whether the code pairs the rows that way. That distinction can change the answer even when all the arithmetic is simple.
Use the free PTCA practice link below to try a different regression snippet. The five-question sample includes a shape-mismatch exercise with an explanation. Start in Study mode, predict the shape of the unreduced errors on paper, then compare your reasoning with the solution.
Your next steps
- Match prediction and target shapes immediately before MSELoss.
- Inspect unreduced errors to catch a grid of unintended pairwise comparisons.
- Explicitly add or remove the feature axis and check the final batch with one example.
Sources & official resources
Linked resources checked on 2026-11-30. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →