Skip to content

← Tensor Foundations step 4 of 7

Easy Framework

Broadcasting Addition

Add the same bias vector to every row of a matrix. Each column has its own bias value, reused across all rows.

Your task

Implement add_bias(x, bias) for floating-point inputs with the same dtype and device. The matrix x has shape (m, n) and bias has shape (n,). Return shape (m, n), preserving dtype and device and leaving both inputs unchanged.

output[i, j] = x[i, j] + bias[j]

For x=[[1, 2, 3], [4, 5, 6]] and bias=[10, 20, 30], return [[11, 22, 33], [14, 25, 36]]. Column 0 receives 10 in every row; column 1 receives 20; column 2 receives 30.

Both frameworks handle this with x + bias. Broadcasting aligns dimensions from the right: the vector's length n matches the matrix's last dimension. Its missing row dimension is treated as size 1 and reused across m rows. You do not need to create m copies of the bias.

Keep bias as a vector or a row of shape (1, n). Reshaping it to (n, 1) changes its alignment and can either fail or add along the wrong direction. The diagram shows the intended shapes.

Loading visualization…