Split a fused QKV checkpoint weight into separate projections
Why it matters Porting pretrained GPT-2 weights into a from-scratch model needs exactly this split, and a missing transpose is the classic bug.
Loading pretrained GPT-2 style weights into your own model often means unpacking a fused attention weight. Such checkpoints store one (d, 3d) matrix used as x @ W + b, with the query, key and value columns side by side, while a typical Linear layer stores (d_out, d_in) and computes x @ W.T + b.
Write split_fused_qkv(W, b). W is (d, 3d) and b is (3d,), with columns [query | key | value], each block d columns wide. Return a dict with "Wq", "Wk", "Wv" in Linear layout (d_out, d_in), so x @ Wq.T + bq equals the query part of x @ W + b, and "bq", "bk", "bv" of shape (d,). Raise ValueError if W.shape[1] != 3 * W.shape[0].
def split_fused_qkv(W, b)Example
split_fused_qkv(np.arange(12).reshape(2, 6), np.arange(6)) gives Wq = [[0, 6], [1, 7]], Wk = [[2, 8], [3, 9]], Wv = [[4, 10], [5, 11]], bq = [0, 1], bk = [2, 3], bv = [4, 5].
Understand the idea
Different code bases store the same linear layer in different layouts. Some store W with shape (d_in, d_out) and compute x W; the common Linear convention stores (d_out, d_in) and computes x W^T. GPT-2 style checkpoints also fuse the three attention projections into one matrix to save a kernel launch. Loading such weights is like converting a recipe from cups to grams: same dish, different units.
Example: d = 2, fused W has 6 columns. Columns 0 to 1 are the query block [[0, 1], [6, 7]]. Transposed, Wq = [[0, 6], [1, 7]]. Check: for x = [1, 0], x W gives [0, 1] in the query columns, and x Wq^T gives [0, 1] as well.
Rule: for i in q, k, v: W_i = W[:, i*d:(i+1)*d]^T and b_i = b[i*d:(i+1)*d].
Because attention blocks are square, a missing transpose does not raise any shape error. The only reliable check is to compare a forward pass against the original layer, as one of the tests does.
Shapes and data flow
W (d, 3d) -> three blocks (d, d) -> transposed (d, d) each; b (3d,) -> three (d,)