Broadcasting Bias Addition ([B, D] + [D]) in PyTorch

Basics
BasicsPyTorchBroadcastingGoogleMetaAmazon

Problem

Given a batch of activations X with shape (B, D) and a 1D bias vector b with shape (D,), implement add_bias(X, b) using PyTorch broadcasting so b is added elementwise to every row of X.

Why It Matters: Every linear layer (XW+bXW + b) and convolution bias relies on broadcasting [B, D] + [D] without allocating redundant copies of b in GPU memory.

Function Signature

import torch

def add_bias(X: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """Add 1D bias b [D] to every row of 2D batch X [B, D]."""

Sample Input & Output

Example 1: 2-Sample Batch With 3 Features

Input:

X = torch.tensor([[1., 2., 3.], [4., 5., 6.]]), b = torch.tensor([10., 20., 30.])

Expected Output:

tensor([[11., 22., 33.], [14., 25., 36.]])

Explanation: b broadcasts along axis 0 so [10, 20, 30] is added to both row 0 and row 1.

Example 2: Negative & Zero Biases

Input:

X = torch.tensor([[5., -2.]]), b = torch.tensor([-5., 0.])

Expected Output:

tensor([[0., -2.]])

Explanation: Even with batch size B = 1, the output preserves 2D shape (1, 2).

Constraints & Edge Cases

  • Return a tensor of shape [B, D].
  • Avoid Python loops over batch rows—vectorized X + b runs in a single fused kernel.
  • Output shape must match X.shape (B, D).

Constraints & Evaluation Criteria

  • Return a tensor of shape `[B, D]`.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
[[1,2],[3,4]] + [10,20]
Expected Output / Criteria
[[11,22],[13,24]]