Skip to content

← Broadcasting step 6 of 6

Easy Primitives

One bias, every position

Jump to the task

To add one bias value per channel, first locate the channel axis. Here the activations have shape (batch, time, channels) and the bias has shape (channels,).

Broadcasting aligns dimensions from the right:

activations: (batch, time, channels)
bias:                    (channels,)
aligned as:  (    1,    1, channels)
result:      (batch, time, channels)

The singleton dimensions let the same channel biases apply at every time step and to every batch item. No explicit reshape is needed.

import torch

x = torch.zeros(1, 2, 3)
bias = torch.tensor([1.0, 2.0, 3.0])
print((x + bias).tolist())
# [[[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]]

Check the layout, not just the dimension sizes

Features are not always on the last axis. For an image tensor shaped (batch, channels, height, width), a channel bias needs a shape such as (1, channels, 1, 1). A convolution layer handles its bias internally; adding a bare channel vector to an NCHW tensor is not generally equivalent.

The starter reshapes the bias to (1, channels, 1), placing its values on the time axis instead. If time and channels differ, this can raise an error or expand an unintended singleton dimension. If they match, the addition can run while applying the wrong bias to each channel. Matching sizes do not prove that the axes have the intended meaning.

Your task

def add_bias(x: torch.Tensor, bias: torch.Tensor) -> torch.Tensor

x has shape (batch, time, channels) and bias has shape (channels,). Return a tensor of the same shape as x, with bias[c] added to every x[b, t, c]. Use broadcasting rather than constructing repeated copies of the bias.