Attention with trainable prefix keys and values (prefix tuning)

MediumFine-tuningPro

Prefix tuning keeps the model frozen and learns a few extra key/value vectors per layer that every token can attend to, like virtual tokens placed before the prompt. Getting the mask right matters: prefix slots sit before position 0, so they are visible to every real token.

Write prefix_attention(q, k, v, pk, pv). q, k, v have shape (T, d) for the real tokens. pk, pv have shape (P, d) for the prefix.
- keys = concatenate(pk, k), values = concatenate(pv, v), shape (P + T, d)
- scores[t] = keys @ q[t] / sqrt(d)
- query t may attend to ALL P prefix slots and to real positions 0..t (causal over real tokens only)
- softmax over the allowed slots, then weight the values
Return the output of shape (T, d).

Signaturedef prefix_attention(q, k, v, pk, pv)

Understand the idea

Prefix tuning freezes the model and learns a few extra key and value vectors per layer. Think of them as invisible tokens sitting before the prompt. Since they come before position 0, every real token can see all of them, while real tokens still only see real tokens up to themselves. Worked example: P = 1, T = 2, d = 1, prefix key [0] with value [10], real keys [0], [0] with values [2], [4]. All scores are 0, so the softmax is uniform over the allowed slots. Token 0 may see the prefix and itself: (10 + 2) / 2 = 6. Token 1 may see the prefix, token 0 and itself: (10 + 2 + 4) / 3 = 5.333. Rule: keys = [pk; k], values = [pv; v]; scores[t] = keys q[t] / sqrt(d); allow all P prefix slots plus real slots 0 to t, block the rest; softmax over allowed slots and weight the values; output shape (T, d). Applying one lower-triangular mask to the joined keys wrongly hides later prefix slots from early tokens. Prefix tuning is a parameter-efficient fine-tuning method alongside LoRA and prompt tuning.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: 2 prefix slots, 4 tokensprefix_attention(_q, _k, _v, _pk, _pv)
  • Sample 2: one prefix slotprefix_attention(_q, _k, _v, _pk[:1], _pv[:1])