Compute next value in a sequence for a single causal self-attention head.
| 726 | |
| 727 | // Compute next value in a sequence for a single causal self-attention head. |
| 728 | void attn( |
| 729 | float* xout, // (n_heads * v_head_dim,) - output vector |
| 730 | float* atth, // (kv_len,) - scratch space to hold attention scores of the sequence |
| 731 | const float* qh, // (head_dim,) - query vector for this head |
| 732 | const f16_t* kh, // (kv_len, n_heads, head_dim) - buffer containing key vectors of the sequence for all KV heads |
| 733 | const f16_t* vh, // (kv_len, n_heads, v_head_dim) - buffer containing value vectors of the sequence for all KV heads |
| 734 | int head_dim, // size of the "key-space" |
| 735 | int v_head_dim, // size of the "value-space" |
| 736 | int n_heads, // number of attention heads |
| 737 | int kv_len // number of tokens of the sequence we will attend over |
| 738 | ) { |
| 739 | int k_stride = n_heads * head_dim; // stride per token in this k head |
| 740 | // calculate attention scores as dot products of q and k |
| 741 | for (int t = 0; t < kv_len; ++t) { |
| 742 | float score = 0.0f; |
| 743 | for (int i = 0; i < head_dim; ++i) { |
| 744 | score += qh[i] * half_to_float(kh[t * k_stride + i]); |
| 745 | } |
| 746 | score /= sqrtf(head_dim); |
| 747 | atth[t] = score; |
| 748 | } |
| 749 | |
| 750 | // softmax the scores to get attention weights over [0..kv_len) |
| 751 | softmax(atth, atth, kv_len); |
| 752 | |
| 753 | int v_stride = n_heads * v_head_dim; // stride per token in this v head |
| 754 | // mix values with attention weights |
| 755 | for (int i = 0; i < v_head_dim; ++i) { |
| 756 | float vi = 0.0f; |
| 757 | for (int t = 0; t < kv_len; ++t) { |
| 758 | vi += atth[t] * half_to_float(vh[t * v_stride + i]); |
| 759 | } |
| 760 | xout[i] = vi; |
| 761 | } |
| 762 | } |
| 763 | |
| 764 | // Compute next value in a sequence for a single causal self-attention head. |
| 765 | // MLA variant: uses combined latent-KV cache and PE-KV cache. |