Add per-query and per-document biases to a score matrix with broadcasting

Why it matters Bias terms in matrix factorization, attention score biases and retrieval score calibration are all broadcast additions.

Retrieval and recommendation models often score pairs as a dot product plus a query bias plus a document bias. Broadcasting adds the two bias vectors along the right axes without building any loops or tiled copies.

Write biased_scores(S, q_bias, d_bias). S has shape (Q, D), q_bias shape (Q,), d_bias shape (D,). Return S[i, j] + q_bias[i] + d_bias[j] as a (Q, D) float array.

Signaturedef biased_scores(S, q_bias, d_bias)

Example

S = [[0, 0], [1, 1]], q_bias [10, 20], d_bias [1, 2] gives [[11, 12], [22, 23]].

Understand the idea

Broadcasting lets arrays of different shapes combine by stretching length-1 axes. Shapes are compared from the right; two axes match if they are equal or one of them is 1. A plain (Q,) vector lines up with the LAST axis, so to add it along rows you must make it (Q, 1).

Worked example: S = [[0, 0], [1, 1]], q = [10, 20] as a column, d = [1, 2] as a row. Row 0: 0 + 10 + 1 = 11 and 0 + 10 + 2 = 12. Row 1: 1 + 20 + 1 = 22 and 1 + 20 + 2 = 23.

Rule: out[i, j] = S[i, j] + q[i] + d[j], written S + q[:, None] + d[None, :]. Shapes: (Q, D) + (Q, 1) + (1, D) -> (Q, D).

Matrix factorization recommenders, attention bias masks and pairwise score tables are built with this.

Shapes and data flow

S (Q, D) + q (Q, 1) + d (1, D) -> (Q, D)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplebiased_scores([[0, 0], [1, 1]], [10, 20], [1, 2])
  • Sample 2: square but asymmetricbiased_scores(np.eye(3), [1, 2, 3], [100, 200, 300])
  • Test 3: rectangularbiased_scores(np.zeros((2, 3)), [1, -1], [0.5, 0.0, -0.5])