8. 使用 broadcasting 为 score matrix 添加 per-query 和 per-document bias
重要性 Matrix factorization 中的 bias terms、attention score biases 以及 retrieval score calibration 都是 broadcast additions。
Retrieval 和 recommendation 模型通常将 pair 的得分计算为 dot product 加上 query bias 和 document bias。Broadcasting 可以沿着正确的 axis 添加这两个 bias vector,而无需构建任何 loops 或 tiled copies。
编写 biased_scores(S, q_bias, d_bias)。S 的 shape 为 (Q, D),q_bias shape 为 (Q,),d_bias shape 为 (D,)。返回 S[i, j] + q_bias[i] + d_bias[j] 形式的 (Q, D) float array。
def biased_scores(S, q_bias, d_bias)示例 1
输入: S = [[0, 0], [1, 1]], q_bias [10, 20], d_bias [1, 2]
输出: [[11, 12], [22, 23]]
示例 2
输入: S = np.eye(3), q_bias = [1, 2, 3], d_bias = [100, 200, 300]
输出: [[102.0, 201.0, 301.0], [102.0, 203.0, 302.0], [103.0, 203.0, 304.0]]
示例 3
输入: S = np.zeros((2, 3)), q_bias = [1, -1], d_bias = [0.5, 0.0, -0.5]
输出: [[1.5, 1.0, 0.5], [-0.5, -1.0, -1.5]]
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
将 q_bias reshape 为 (Q, 1),将 d_bias reshape 为 (1, D),以便它们能沿着行和列进行 broadcast。
提示 2
每个 bias 必须与 S 的一个 axis 对齐。
提示 3
添加一个长度为 1 的 axis 来指定 vector 遵循哪个 axis。
提示 4
q[:, None] 用于行,d[None, :] 用于列。
常见错误
- 直接添加 (Q,) vector,这会使其与最后一个 axis(列)对齐。
- 仅测试 square shapes,在这种情况下错误的 axis 不会抛出错误。
理解思路
Broadcasting 通过拉伸长度为 1 的 axis,让不同 shape 的 arrays 进行组合。Shape 从右侧开始比较;如果两个 axis 相等或其中一个是 1,则它们匹配。一个普通的 (Q,) vector 会与最后一个 axis 对齐,因此要沿着行(rows)添加它,必须将其变为 (Q, 1)。
S = [[0, 0], [1, 1]], q = [10, 20] 作为一列, d = [1, 2] 作为一行。Row 0: 0 + 10 + 1 = 11 且 0 + 10 + 2 = 12。Row 1: 1 + 20 + 1 = 22 且 1 + 20 + 2 = 23。
out[i, j] = S[i, j] + q[i] + d[j], 写法为 S + q[:, None] + d[None, :]
Shapes: (Q, D) + (Q, 1) + (1, D) -> (Q, D).
Matrix factorization recommenders、attention bias masks 和 pairwise score tables 都是利用这一点构建的。
Shape 与数据流
S (Q, D) + q (Q, 1) + d (1, D) -> (Q, D)