src/cpu/flash_attention.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // CPU backend — flash-attention family (CHUNK 6). | ||
| 2 | // | ||
| 3 | // Ground truth: src/cuda/flash_attention.cu and | ||
| 4 | // src/cuda/flash_attention_backward.cu. | ||
| 5 | // | ||
| 6 | // Six ops: | ||
| 7 | // * flash_attention_forward — SDPA over pre-projected QKV. | ||
| 8 | // * flash_attention_qkvo_forward — fused QKVO projections + SDPA. | ||
| 9 | // * flash_attention_qkvo_backward — full backward of the above. | ||
| 10 | // * flash_attention_backward — backward over pre-projected QKV. | ||
| 11 | // * flash_attention_project_kv — project ctx → K_out, V_out. | ||
| 12 | // * flash_attention_q_with_kv_cached_forward — project X→Q, attend cached K/V, | ||
| 13 | // project through Wo. | ||
| 14 | // | ||
| 15 | // DTYPE DECISIONS | ||
| 16 | // Every CUDA op in this family runs FP16 internally (Q/K/V/weights all FP16, | ||
| 17 | // attention core in FP16). The CPU backend is FP32-only (per CLAUDE.md), so | ||
| 18 | // all six CPU impls run the straightforward FP32 scalar math that produces | ||
| 19 | // the SAME mathematical result as the GPU's tiled flash kernels — flash | ||
| 20 | // tiling is a memory optimisation, not a different result, so a plain | ||
| 21 | // materialised attention is correct. The parity tests quantise inputs | ||
| 22 | // through FP16 (so both backends start identical), feed FP16 to the GPU and | ||
| 23 | // FP32 to the CPU, and compare with a loose FP16-scale tolerance. | ||
| 24 | // | ||
| 25 | // CONVENTIONS (verified against flash_attention.cu / *_backward.cu) | ||
| 26 | // * Q/K/V are (Lq|Lk, D) with D = num_heads * head_dim, the head dimension | ||
| 27 | // contiguous within each row: element (l, h*head_dim + d). | ||
| 28 | // * Softmax scale: 1/sqrt(head_dim). | ||
| 29 | // * Mask: length-Lk key-validity buffer (1=valid, 0=invalid). mask[k] <= 0.5 | ||
| 30 | // drops key k from the softmax (score → -inf). A fully-masked row yields a | ||
| 31 | // zero output row (rsum == 0 ⇒ inv == 0). Mask never gates query rows. | ||
| 32 | // * Causal: key k contributes to query q only when k <= q (requires Lq==Lk). | ||
| 33 | // * Projection weight layout (linear_forward_batched_fp16): Wq/Wo are (D, D); | ||
| 34 | // Wk/Wv are (D, D_ctx). out(i, n) = sum_k In(i, k) * W(n, k) + b(n) — i.e. | ||
| 35 | // In @ W^T, optional bias broadcast over rows. | ||
| 36 | // * flash_attention_qkvo_forward: Ctx==null ⇒ self-attention (kv_src = X); | ||
| 37 | // non-null ⇒ cross-attention. | ||
| 38 | // | ||
| 39 | // ACCUMULATION (verified against the CUDA backward kernels) | ||
| 40 | // * flash_attention_backward: dQ/dK/dV OVERWRITTEN (CUDA zeros then | ||
| 41 | // fills each per-head slot). | ||
| 42 | // * flash_attention_qkvo_backward: dX OVERWRITTEN (CUDA zeros it, then the | ||
| 43 | // single fa_fp16_add of dX_from_Q makes | ||
| 44 | // it equal that path; self-attn adds the | ||
| 45 | // K/V paths on top). dCtx OVERWRITTEN | ||
| 46 | // (zeroed then K+V paths added). | ||
| 47 | // dWq/dWk/dWv/dWo and dbq/dbk/dbv/dbo | ||
| 48 | // ACCUMULATE (+=) — linear_backward_batched | ||
| 49 | // folds into the caller's grad buffers. | ||
| 50 | |||
| 51 | #include <brotensor/tensor.h> | ||
| 52 | #include <brotensor/detail/cpu/thread_pool.h> | ||
| 53 | |||
| 54 | #include <algorithm> | ||
| 55 | #include <cmath> | ||
| 56 | #include <stdexcept> | ||
| 57 | #include <vector> | ||
| 58 | |||
| 59 | namespace brotensor::detail::cpu { | ||
| 60 | |||
| 61 | namespace { | ||
| 62 | |||
| 63 | using ::brotensor::Tensor; | ||
| 64 | using ::brotensor::Dtype; | ||
| 65 | |||
| 66 | // out(i, n) = sum_k In(i, k) * W(n, k) + (bias ? bias[n] : 0). | ||
| 67 | // In : (M, Din) W : (Dout, Din) bias : (Dout,) optional out : (M, Dout) | ||
| 68 | // Each token i owns row i of Out exclusively (In/W/bias read-only), so the | ||
| 69 | // token axis parallelizes with no cross-thread writes. | ||
| 70 | 107 | void linear_proj(const float* In, const float* W, const float* bias, | |
| 71 | float* Out, int M, int Din, int Dout) { | ||
| 72 | 1058 | parallel_for(static_cast<std::size_t>(M), [&](std::size_t ii) { | |
| 73 | 951 | const int i = static_cast<int>(ii); | |
| 74 | 951 | const float* xr = In + static_cast<std::size_t>(i) * Din; | |
| 75 | 951 | float* orow = Out + static_cast<std::size_t>(i) * Dout; | |
| 76 | 37944 | for (int n = 0; n < Dout; ++n) { | |
| 77 | 36993 | const float* wr = W + static_cast<std::size_t>(n) * Din; | |
| 78 | 36993 | float acc = bias ? bias[n] : 0.0f; | |
| 79 | 1452425 | for (int k = 0; k < Din; ++k) acc += xr[k] * wr[k]; | |
| 80 | 36993 | orow[n] = acc; | |
| 81 | 36993 | } | |
| 82 | 951 | }); | |
| 83 | 107 | } | |
| 84 | |||
| 85 | // Backward of linear_proj. forward: Out = In @ W^T + b. | ||
| 86 | // dIn(i, k) = sum_n dOut(i, n) * W(n, k) — accumulate into dIn. | ||
| 87 | // dW(n, k) += sum_i dOut(i, n) * In(i, k) — accumulate. | ||
| 88 | // db(n) += sum_i dOut(i, n) — accumulate (if db != null). | ||
| 89 | 36 | void linear_proj_backward(const float* In, const float* W, const float* dOut, | |
| 90 | float* dIn, float* dW, float* db, | ||
| 91 | int M, int Din, int Dout) { | ||
| 92 | // Each i owns row i of dIn exclusively: the "+=" here accumulates onto | ||
| 93 | // that row's pre-existing value (from before this call), never onto | ||
| 94 | // another i's row, so this parallelizes over i (the token axis). | ||
| 95 | 340 | parallel_for(static_cast<std::size_t>(M), [&](std::size_t ii) { | |
| 96 | 304 | const int i = static_cast<int>(ii); | |
| 97 | 304 | const float* dor = dOut + static_cast<std::size_t>(i) * Dout; | |
| 98 | 304 | float* dir = dIn + static_cast<std::size_t>(i) * Din; | |
| 99 | 10012 | for (int k = 0; k < Din; ++k) { | |
| 100 | 9708 | float acc = 0.0f; | |
| 101 | 356943 | for (int n = 0; n < Dout; ++n) | |
| 102 | 347235 | acc += dor[n] * W[static_cast<std::size_t>(n) * Din + k]; | |
| 103 | 9708 | dir[k] += acc; | |
| 104 | 9708 | } | |
| 105 | 304 | }); | |
| 106 | // dW/db: n-outer with a private serial sum over i (the reduction axis) — | ||
| 107 | // each n owns row n of dW and scalar db[n] exclusively, written exactly | ||
| 108 | // once, so this parallelizes over n (Dout). | ||
| 109 | 1380 | parallel_for(static_cast<std::size_t>(Dout), [&](std::size_t ni) { | |
| 110 | 1344 | const int n = static_cast<int>(ni); | |
| 111 | 1344 | float dbacc = 0.0f; | |
| 112 | 44354 | for (int k = 0; k < Din; ++k) { | |
| 113 | 43010 | float dw = 0.0f; | |
| 114 | 383862 | for (int i = 0; i < M; ++i) | |
| 115 | 681704 | dw += dOut[static_cast<std::size_t>(i) * Dout + n] * | |
| 116 | 340852 | In[static_cast<std::size_t>(i) * Din + k]; | |
| 117 | 43010 | dW[static_cast<std::size_t>(n) * Din + k] += dw; | |
| 118 | 43010 | } | |
| 119 | 12594 | for (int i = 0; i < M; ++i) | |
| 120 | 11250 | dbacc += dOut[static_cast<std::size_t>(i) * Dout + n]; | |
| 121 | 1344 | if (db) db[n] += dbacc; | |
| 122 | 1344 | }); | |
| 123 | 36 | } | |
| 124 | |||
| 125 | // Materialised multi-head attention over pre-projected Q/K/V. | ||
| 126 | // Q : (Lq, D) K, V : (Lk, D) D = H * hd. | ||
| 127 | // O : (Lq, D) — written. | ||
| 128 | // P (optional, may be null): (H*Lq, Lk) per-head softmax probabilities. | ||
| 129 | // scale = 1/sqrt(hd); key mask + causal applied during the row softmax. | ||
| 130 | // window > 0 adds a sliding causal band: query q attends only keys | ||
| 131 | // k in [q-window+1, q] (window <= 0 leaves the band unbounded). | ||
| 132 | // Q/O are H heads wide (Dq = H*hd); K/V may be grouped (Dkv = (H/group)*hd, | ||
| 133 | // GQA) — query head h reads K/V head h/group. group == 1 / Dkv < 0 is plain MHA. | ||
| 134 | // scratch_scores, if non-null, must point at a caller-owned buffer of at | ||
| 135 | // least Lk floats and is reused verbatim (no allocation here) — callers | ||
| 136 | // looping over many short sequences (e.g. varlen attention) hoist one buffer | ||
| 137 | // sized to the batch's max Lk instead of paying a heap allocation per call. | ||
| 138 | // A null scratch_scores falls back to a local per-call allocation, matching | ||
| 139 | // the original single-call behavior. | ||
| 140 | // | ||
| 141 | // THREADING: when scratch_scores is null (every caller except the varlen | ||
| 142 | // family), the outer q loop is safe to parallelize because each q's row of | ||
| 143 | // O/P is written exclusively by that q (see per-iteration comments below); | ||
| 144 | // the only shared mutable state is the `scores` scratch buffer, so the | ||
| 145 | // parallel path gives every q its own private Lk-wide slice of a | ||
| 146 | // freshly-allocated Lq*Lk buffer instead of one buffer reused across q. | ||
| 147 | // When scratch_scores is non-null, the caller (flash_attention_varlen_*) | ||
| 148 | // has explicitly hoisted ONE Lk-sized buffer across many sequential calls | ||
| 149 | // to this function (one per sequence in a batch) specifically to avoid | ||
| 150 | // per-sequence allocation; parallelizing the q loop in that case would have | ||
| 151 | // every thread's q race on that single shared buffer, so this path is left | ||
| 152 | // exactly as it was (serial, reusing the caller's buffer verbatim) — see | ||
| 153 | // flash_attention_varlen_forward's own comment for why it stays | ||
| 154 | // single-threaded. | ||
| 155 | 193 | void attention_core(const float* Q, const float* K, const float* V, | |
| 156 | const float* mask, int Lq, int Lk, int D, int H, | ||
| 157 | bool causal, float* O, float* P, int window = 0, | ||
| 158 | int q_offset = 0, int Dkv = -1, int group = 1, | ||
| 159 | float* scratch_scores = nullptr) { | ||
| 160 | 193 | const int hd = D / H; | |
| 161 | 193 | if (Dkv < 0) Dkv = D; | |
| 162 | 193 | const float inv_sqrt = 1.0f / std::sqrt(static_cast<float>(hd)); | |
| 163 | |||
| 164 | // Per-q body. `scores` must be a private Lk-wide buffer when running | ||
| 165 | // concurrently with other q's (see threading note above) — each q | ||
| 166 | // writes only row q of O (and, if requested, the q-th row of every | ||
| 167 | // head's P segment), so distinct q's never touch the same output bytes. | ||
| 168 | 9452 | auto process_q = [&](int q, float* scores) { | |
| 169 | 9259 | const int aq = q + q_offset; // absolute causal position of this query | |
| 170 | 37141 | for (int h = 0; h < H; ++h) { | |
| 171 | 27882 | const int off = h * hd; // Q/O head offset (Dq-wide) | |
| 172 | 27882 | const int off_kv = (h / group) * hd; // K/V head offset (Dkv-wide) | |
| 173 | 27882 | float m = -1e30f; | |
| 174 | 4392159 | for (int k = 0; k < Lk; ++k) { | |
| 175 | 4364277 | if (mask && mask[k] <= 0.5f) { scores[k] = -1e30f; continue; } | |
| 176 | 4283271 | if (causal && k > aq) { scores[k] = -1e30f; continue; } | |
| 177 | 3577896 | if (causal && window > 0 && k <= aq - window) { scores[k] = -1e30f; continue; } | |
| 178 | 3543372 | if (!causal && window > 0 && std::abs(k - aq) > window / 2) { scores[k] = -1e30f; continue; } | |
| 179 | 3471636 | const float* qr = Q + static_cast<std::size_t>(q) * D + off; | |
| 180 | 3471636 | const float* kr = K + static_cast<std::size_t>(k) * Dkv + off_kv; | |
| 181 | 3471636 | float dot = 0.0f; | |
| 182 | 222647478 | for (int d = 0; d < hd; ++d) dot += qr[d] * kr[d]; | |
| 183 | 3471636 | const float s = dot * inv_sqrt; | |
| 184 | 3471636 | scores[k] = s; | |
| 185 | 3471636 | if (s > m) m = s; | |
| 186 | 3471636 | } | |
| 187 | 27882 | const bool empty = (m <= -1e29f); | |
| 188 | 27882 | float sum = 0.0f; | |
| 189 | 4449914 | for (int k = 0; k < Lk; ++k) { | |
| 190 | 4422032 | const float e = empty ? 0.0f : std::exp(scores[k] - m); | |
| 191 | 4422032 | scores[k] = e; | |
| 192 | 4422032 | sum += e; | |
| 193 | 4422032 | } | |
| 194 | 27882 | const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; | |
| 195 | 27882 | float* orow = O + static_cast<std::size_t>(q) * D + off; | |
| 196 | 1569727 | for (int d = 0; d < hd; ++d) { | |
| 197 | 1541845 | float acc = 0.0f; | |
| 198 | 248113950 | for (int k = 0; k < Lk; ++k) { | |
| 199 | 493144210 | acc += scores[k] * inv * | |
| 200 | 246572105 | V[static_cast<std::size_t>(k) * Dkv + off_kv + d]; | |
| 201 | 246572105 | } | |
| 202 | 1541845 | orow[d] = acc; | |
| 203 | 1541845 | } | |
| 204 | 27882 | if (P) { | |
| 205 | ✗ | float* prow = | |
| 206 | ✗ | P + (static_cast<std::size_t>(h) * Lq + q) * Lk; | |
| 207 | ✗ | for (int k = 0; k < Lk; ++k) prow[k] = scores[k] * inv; | |
| 208 | ✗ | } | |
| 209 | 27882 | } | |
| 210 | 9259 | }; | |
| 211 | |||
| 212 | 193 | if (scratch_scores) { | |
| 213 | // Varlen path: caller owns a single Lk-sized buffer reused across | ||
| 214 | // many sequential calls to this function. Stay serial (see the | ||
| 215 | // threading note above). | ||
| 216 | 2855 | for (int q = 0; q < Lq; ++q) process_q(q, scratch_scores); | |
| 217 | 81 | } else { | |
| 218 | // Every other caller: parallelize over q, each q privately slicing | ||
| 219 | // a freshly allocated Lq*Lk buffer so concurrent q's never share a | ||
| 220 | // `scores` row. | ||
| 221 | 224 | std::vector<float> scores_all(static_cast<std::size_t>(Lq) * | |
| 222 | 112 | static_cast<std::size_t>(Lk)); | |
| 223 | 6599 | parallel_for(static_cast<std::size_t>(Lq), [&](std::size_t qi) { | |
| 224 | 6487 | const int q = static_cast<int>(qi); | |
| 225 | 6487 | process_q(q, scores_all.data() + static_cast<std::size_t>(q) * Lk); | |
| 226 | 6487 | }); | |
| 227 | 112 | } | |
| 228 | 193 | } | |
| 229 | |||
| 230 | // Per-head flash-attention backward over pre-projected Q/K/V. Recompute P, | ||
| 231 | // then dV = P^T·dO_attn, dP = dO_attn·V^T, dS = P*(dP - D_q)*scale, | ||
| 232 | // dQ = dS·K, dK = dS^T·Q. dQ/dK/dV are OVERWRITTEN. | ||
| 233 | // | ||
| 234 | // scratch_P/scratch_dP/scratch_dS, if all non-null, must each point at a | ||
| 235 | // caller-owned buffer of at least Lq*Lk floats and are reused verbatim (no | ||
| 236 | // allocation here) — callers looping over many short sequences (e.g. varlen | ||
| 237 | // attention backward) hoist one triple of buffers sized to the batch's max | ||
| 238 | // Lq*Lk instead of paying three heap allocations per call. Leaving any of | ||
| 239 | // them null falls back to a local per-call allocation, matching the original | ||
| 240 | // single-call behavior. | ||
| 241 | // | ||
| 242 | // THREADING: when the scratch triple is null (every caller except the | ||
| 243 | // varlen family), the outer h loop is safe to parallelize — each head h | ||
| 244 | // writes only its own column range [h*hd, h*hd+hd) of dQ/dK/dV (never | ||
| 245 | // touched by another h), so the only shared mutable state is P/dP/dS, which | ||
| 246 | // the parallel path gives each h its own private Lq*Lk slice of a | ||
| 247 | // freshly-allocated H*Lq*Lk buffer instead of one triple reused across h. | ||
| 248 | // When the scratch triple is supplied, the caller | ||
| 249 | // (flash_attention_varlen_backward) has explicitly hoisted ONE Lq*Lk-sized | ||
| 250 | // triple across many sequential calls to this function (one per sequence in | ||
| 251 | // a batch); parallelizing the h loop in that case would have every thread's | ||
| 252 | // h race on that single shared triple, so this path is left exactly as it | ||
| 253 | // was (serial, reusing the caller's buffers verbatim). | ||
| 254 | 64 | void attention_core_backward(const float* Q, const float* K, const float* V, | |
| 255 | const float* dO, const float* mask, | ||
| 256 | int Lq, int Lk, int D, int H, bool causal, | ||
| 257 | float* dQ, float* dK, float* dV, | ||
| 258 | float* scratch_P = nullptr, | ||
| 259 | float* scratch_dP = nullptr, | ||
| 260 | float* scratch_dS = nullptr) { | ||
| 261 | 64 | const int hd = D / H; | |
| 262 | 64 | const float inv_sqrt = 1.0f / std::sqrt(static_cast<float>(hd)); | |
| 263 | 13536 | for (std::size_t i = 0; i < static_cast<std::size_t>(Lq) * D; ++i) | |
| 264 | 13472 | dQ[i] = 0.0f; | |
| 265 | 14776 | for (std::size_t i = 0; i < static_cast<std::size_t>(Lk) * D; ++i) { | |
| 266 | 14712 | dK[i] = 0.0f; | |
| 267 | 14712 | dV[i] = 0.0f; | |
| 268 | 14712 | } | |
| 269 | |||
| 270 | // Per-head body. P/dP/dS must be a private Lq*Lk buffer when running | ||
| 271 | // concurrently with other heads (see threading note above) — each h | ||
| 272 | // writes only its own column range of dQ/dK/dV, so distinct h's never | ||
| 273 | // touch the same output bytes. | ||
| 274 | 237 | auto process_head = [&](int h, float* P, float* dP, float* dS) { | |
| 275 | 173 | const int off = h * hd; | |
| 276 | // Recompute P for this head. | ||
| 277 | 1419 | for (int q = 0; q < Lq; ++q) { | |
| 278 | 1246 | float m = -1e30f; | |
| 279 | 1246 | float* prow = P + static_cast<std::size_t>(q) * Lk; | |
| 280 | 13126 | for (int k = 0; k < Lk; ++k) { | |
| 281 | 11880 | if (mask && mask[k] <= 0.5f) { prow[k] = -1e30f; continue; } | |
| 282 | 11528 | if (causal && k > q) { prow[k] = -1e30f; continue; } | |
| 283 | 10616 | const float* qr = Q + static_cast<std::size_t>(q) * D + off; | |
| 284 | 10616 | const float* kr = K + static_cast<std::size_t>(k) * D + off; | |
| 285 | 10616 | float dot = 0.0f; | |
| 286 | 134000 | for (int d = 0; d < hd; ++d) dot += qr[d] * kr[d]; | |
| 287 | 10616 | prow[k] = std::clamp(dot * inv_sqrt, -1e29f, 1e29f); | |
| 288 | 10616 | if (prow[k] > m) m = prow[k]; | |
| 289 | 10616 | } | |
| 290 | 1246 | const bool empty = (m <= -1e29f); | |
| 291 | 1246 | float sum = 0.0f; | |
| 292 | 13126 | for (int k = 0; k < Lk; ++k) { | |
| 293 | 11880 | const float e = empty ? 0.0f : std::exp(prow[k] - m); | |
| 294 | 11880 | prow[k] = e; | |
| 295 | 11880 | sum += e; | |
| 296 | 11880 | } | |
| 297 | 1246 | const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; | |
| 298 | 13126 | for (int k = 0; k < Lk; ++k) prow[k] *= inv; | |
| 299 | 1246 | } | |
| 300 | // dV[k, off+d] = sum_q P[q,k] * dO[q, off+d]. | ||
| 301 | 1565 | for (int k = 0; k < Lk; ++k) { | |
| 302 | 1392 | float* dvr = dV + static_cast<std::size_t>(k) * D + off; | |
| 303 | 16090 | for (int d = 0; d < hd; ++d) { | |
| 304 | 14698 | float acc = 0.0f; | |
| 305 | 152834 | for (int q = 0; q < Lq; ++q) | |
| 306 | 276272 | acc += P[static_cast<std::size_t>(q) * Lk + k] * | |
| 307 | 138136 | dO[static_cast<std::size_t>(q) * D + off + d]; | |
| 308 | 14698 | dvr[d] = acc; | |
| 309 | 14698 | } | |
| 310 | 1392 | } | |
| 311 | // dP[q,k] = sum_d dO[q, off+d] * V[k, off+d]. | ||
| 312 | 1419 | for (int q = 0; q < Lq; ++q) { | |
| 313 | 13120 | for (int k = 0; k < Lk; ++k) { | |
| 314 | 11874 | float acc = 0.0f; | |
| 315 | 150165 | for (int d = 0; d < hd; ++d) | |
| 316 | 276582 | acc += dO[static_cast<std::size_t>(q) * D + off + d] * | |
| 317 | 138291 | V[static_cast<std::size_t>(k) * D + off + d]; | |
| 318 | 11874 | dP[static_cast<std::size_t>(q) * Lk + k] = acc; | |
| 319 | 11874 | } | |
| 320 | 1246 | } | |
| 321 | // dS[q,k] = P[q,k] * (dP[q,k] - D_q) * inv_sqrt. | ||
| 322 | 1419 | for (int q = 0; q < Lq; ++q) { | |
| 323 | 1246 | const float* prow = P + static_cast<std::size_t>(q) * Lk; | |
| 324 | 1246 | const float* dpr = dP + static_cast<std::size_t>(q) * Lk; | |
| 325 | 1246 | float* dsr = dS + static_cast<std::size_t>(q) * Lk; | |
| 326 | 1246 | float Dq = 0.0f; | |
| 327 | 13126 | for (int k = 0; k < Lk; ++k) if (prow[k] > 0.0f && std::isfinite(dpr[k])) Dq += prow[k] * dpr[k]; | |
| 328 | 13126 | for (int k = 0; k < Lk; ++k) | |
| 329 | 11880 | dsr[k] = (prow[k] > 0.0f && std::isfinite(dpr[k])) ? (prow[k] * (dpr[k] - Dq) * inv_sqrt) : 0.0f; | |
| 330 | 1246 | } | |
| 331 | // dQ[q, off+d] = sum_k dS[q,k] * K[k, off+d]. | ||
| 332 | 1419 | for (int q = 0; q < Lq; ++q) { | |
| 333 | 1246 | float* dqr = dQ + static_cast<std::size_t>(q) * D + off; | |
| 334 | 1246 | const float* dsr = dS + static_cast<std::size_t>(q) * Lk; | |
| 335 | 14718 | for (int d = 0; d < hd; ++d) { | |
| 336 | 13472 | float acc = 0.0f; | |
| 337 | 152088 | for (int k = 0; k < Lk; ++k) | |
| 338 | 277232 | acc += dsr[k] * | |
| 339 | 138616 | K[static_cast<std::size_t>(k) * D + off + d]; | |
| 340 | 13472 | dqr[d] = acc; | |
| 341 | 13472 | } | |
| 342 | 1246 | } | |
| 343 | // dK[k, off+d] = sum_q dS[q,k] * Q[q, off+d]. | ||
| 344 | 1565 | for (int k = 0; k < Lk; ++k) { | |
| 345 | 1392 | float* dkr = dK + static_cast<std::size_t>(k) * D + off; | |
| 346 | 16104 | for (int d = 0; d < hd; ++d) { | |
| 347 | 14712 | float acc = 0.0f; | |
| 348 | 153328 | for (int q = 0; q < Lq; ++q) | |
| 349 | 277232 | acc += dS[static_cast<std::size_t>(q) * Lk + k] * | |
| 350 | 138616 | Q[static_cast<std::size_t>(q) * D + off + d]; | |
| 351 | 14712 | dkr[d] = acc; | |
| 352 | 14712 | } | |
| 353 | 1392 | } | |
| 354 | 173 | }; | |
| 355 | |||
| 356 | 64 | if (scratch_P && scratch_dP && scratch_dS) { | |
| 357 | // Varlen path: caller owns a single Lq*Lk-sized triple reused across | ||
| 358 | // many sequential calls to this function. Stay serial (see the | ||
| 359 | // threading note above). | ||
| 360 | 148 | for (int h = 0; h < H; ++h) | |
| 361 | 102 | process_head(h, scratch_P, scratch_dP, scratch_dS); | |
| 362 | 46 | } else { | |
| 363 | // Every other caller: parallelize over h, each h privately slicing | ||
| 364 | // a freshly allocated H*Lq*Lk buffer so concurrent heads never | ||
| 365 | // share a P/dP/dS segment. | ||
| 366 | 18 | const std::size_t n = static_cast<std::size_t>(Lq) * Lk; | |
| 367 | 18 | std::vector<float> P_all(static_cast<std::size_t>(H) * n); | |
| 368 | 18 | std::vector<float> dP_all(static_cast<std::size_t>(H) * n); | |
| 369 | 18 | std::vector<float> dS_all(static_cast<std::size_t>(H) * n); | |
| 370 | 89 | parallel_for(static_cast<std::size_t>(H), [&](std::size_t hi) { | |
| 371 | 71 | const int h = static_cast<int>(hi); | |
| 372 | 142 | process_head(h, P_all.data() + static_cast<std::size_t>(h) * n, | |
| 373 | 71 | dP_all.data() + static_cast<std::size_t>(h) * n, | |
| 374 | 71 | dS_all.data() + static_cast<std::size_t>(h) * n); | |
| 375 | 71 | }); | |
| 376 | 18 | } | |
| 377 | 64 | } | |
| 378 | |||
| 379 | 256 | inline void ensure_f32(Tensor& t, int r, int c) { | |
| 380 | 256 | if (t.rows != r || t.cols != c || t.dtype != Dtype::FP32) | |
| 381 | 243 | t.resize(r, c, Dtype::FP32); | |
| 382 | 256 | } | |
| 383 | |||
| 384 | } // namespace | ||
| 385 | |||
| 386 | // ─── flash_attention_forward ─────────────────────────────────────────────── | ||
| 387 | |||
| 388 | 35 | void flash_attention_forward(const ::brotensor::Tensor& Q, | |
| 389 | const ::brotensor::Tensor& K, | ||
| 390 | const ::brotensor::Tensor& V, | ||
| 391 | const float* d_mask, | ||
| 392 | int num_heads, | ||
| 393 | bool causal, | ||
| 394 | ::brotensor::Tensor& O) { | ||
| 395 | 35 | const int Lq = Q.rows; | |
| 396 | 35 | const int Lk = K.rows; | |
| 397 | 35 | const int D = Q.cols; | |
| 398 | 35 | if (K.cols != D || V.cols != D || V.rows != Lk) | |
| 399 | ✗ | throw std::runtime_error("flash_attention_forward: shape mismatch"); | |
| 400 | 35 | if (num_heads <= 0 || D % num_heads != 0) | |
| 401 | ✗ | throw std::runtime_error("flash_attention_forward: num_heads must divide D"); | |
| 402 | 35 | if (causal && Lq != Lk) | |
| 403 | ✗ | throw std::runtime_error("flash_attention_forward: causal requires Lq == Lk"); | |
| 404 | 35 | ensure_f32(O, Lq, D); | |
| 405 | 35 | if (Lq == 0 || Lk == 0 || D == 0) return; | |
| 406 | |||
| 407 | 70 | attention_core(Q.host_f32(), K.host_f32(), V.host_f32(), d_mask, | |
| 408 | 35 | Lq, Lk, D, num_heads, causal, O.host_f32_mut(), nullptr); | |
| 409 | 35 | } | |
| 410 | |||
| 411 | // ─── flash_attention_windowed_forward ────────────────────────────────────── | ||
| 412 | // | ||
| 413 | // Sliding-window causal self-attention (FP32, inference-only). Always causal. | ||
| 414 | // The Lq queries occupy the last Lq positions of a length-Lk causal sequence | ||
| 415 | // (q_offset = Lk - Lq): query row r sits at absolute position r + q_offset and | ||
| 416 | // attends keys [max(0, pos-window+1), pos]. window <= 0 is unbounded causal. | ||
| 417 | // - Lq == Lk (q_offset 0): plain causal / sliding window (e.g. the codec). | ||
| 418 | // - Lq < Lk: incremental decode — a short query block (often a single token) | ||
| 419 | // attending the whole K/V cache, the autoregressive step. Lq == 1 with | ||
| 420 | // window <= 0 attends every cached key (full attention over the cache). | ||
| 421 | // Lk >= Lq required. | ||
| 422 | 33 | void flash_attention_windowed_forward(const ::brotensor::Tensor& Q, | |
| 423 | const ::brotensor::Tensor& K, | ||
| 424 | const ::brotensor::Tensor& V, | ||
| 425 | const float* d_mask, | ||
| 426 | int num_heads, | ||
| 427 | int window, | ||
| 428 | ::brotensor::Tensor& O, | ||
| 429 | bool causal) { | ||
| 430 | 33 | const int Lq = Q.rows; | |
| 431 | 33 | const int Lk = K.rows; | |
| 432 | 33 | const int D = Q.cols; // Dq = num_heads * head_dim | |
| 433 | 33 | const int Dkv = K.cols; // n_kv * head_dim (GQA when < D) | |
| 434 | 33 | if (V.cols != Dkv || V.rows != Lk) | |
| 435 | ✗ | throw std::runtime_error("flash_attention_windowed_forward: shape mismatch"); | |
| 436 | 33 | if (num_heads <= 0 || D % num_heads != 0) | |
| 437 | ✗ | throw std::runtime_error("flash_attention_windowed_forward: num_heads must divide D"); | |
| 438 | 33 | const int head_dim = D / num_heads; | |
| 439 | 33 | if (Dkv == 0 || Dkv % head_dim != 0) | |
| 440 | ✗ | throw std::runtime_error("flash_attention_windowed_forward: K/V width must be a head_dim multiple"); | |
| 441 | 33 | const int n_kv = Dkv / head_dim; | |
| 442 | 33 | if (num_heads % n_kv != 0) | |
| 443 | ✗ | throw std::runtime_error("flash_attention_windowed_forward: num_heads must be a multiple of n_kv"); | |
| 444 | 33 | if (Lk < Lq) | |
| 445 | ✗ | throw std::runtime_error("flash_attention_windowed_forward: requires Lk >= Lq"); | |
| 446 | 33 | ensure_f32(O, Lq, D); | |
| 447 | 33 | if (Lq == 0 || Lk == 0 || D == 0) return; | |
| 448 | |||
| 449 | 66 | attention_core(Q.host_f32(), K.host_f32(), V.host_f32(), d_mask, | |
| 450 | 33 | Lq, Lk, D, num_heads, causal, O.host_f32_mut(), | |
| 451 | 33 | nullptr, window, /*q_offset=*/Lk - Lq, Dkv, | |
| 452 | 33 | /*group=*/num_heads / n_kv); | |
| 453 | 33 | } | |
| 454 | |||
| 455 | // ─── flash_attention_gqa_forward ─────────────────────────────────────────── | ||
| 456 | // | ||
| 457 | // GQA generalisation of flash_attention_forward, causal OR bidirectional. Q is | ||
| 458 | // num_q_heads-wide, K/V are num_kv_heads-wide (GQA group = num_q_heads/num_kv_heads; | ||
| 459 | // equal == MHA). causal == false attends every key (the bidirectional encoder | ||
| 460 | // prefill). attention_core already carries the group mapping, the causal flag, | ||
| 461 | // and the key mask, so this is a validate-and-dispatch shim — q_offset is 0 | ||
| 462 | // because the queries occupy positions [0, Lq) (Lq == Lk when causal). | ||
| 463 | 14 | void flash_attention_gqa_forward(const ::brotensor::Tensor& Q, | |
| 464 | const ::brotensor::Tensor& K, | ||
| 465 | const ::brotensor::Tensor& V, | ||
| 466 | const float* d_mask, | ||
| 467 | int num_q_heads, | ||
| 468 | int num_kv_heads, | ||
| 469 | bool causal, | ||
| 470 | ::brotensor::Tensor& O) { | ||
| 471 | 14 | const int Lq = Q.rows; | |
| 472 | 14 | const int Lk = K.rows; | |
| 473 | 14 | const int Dq = Q.cols; // num_q_heads * head_dim | |
| 474 | 14 | const int Dkv = K.cols; // num_kv_heads * head_dim | |
| 475 | 14 | if (num_q_heads <= 0 || num_kv_heads <= 0) | |
| 476 | ✗ | throw std::runtime_error("flash_attention_gqa_forward: head counts must be positive"); | |
| 477 | 14 | if (Dq % num_q_heads != 0) | |
| 478 | ✗ | throw std::runtime_error("flash_attention_gqa_forward: num_q_heads must divide Q.cols"); | |
| 479 | 14 | const int head_dim = Dq / num_q_heads; | |
| 480 | 14 | if (V.cols != Dkv || V.rows != Lk) | |
| 481 | ✗ | throw std::runtime_error("flash_attention_gqa_forward: shape mismatch"); | |
| 482 | 14 | if (Dkv != num_kv_heads * head_dim) | |
| 483 | ✗ | throw std::runtime_error("flash_attention_gqa_forward: K/V width must be num_kv_heads*head_dim"); | |
| 484 | 14 | if (num_q_heads % num_kv_heads != 0) | |
| 485 | ✗ | throw std::runtime_error("flash_attention_gqa_forward: num_kv_heads must divide num_q_heads"); | |
| 486 | 14 | if (causal && Lq != Lk) | |
| 487 | ✗ | throw std::runtime_error("flash_attention_gqa_forward: causal requires Lq == Lk"); | |
| 488 | 14 | ensure_f32(O, Lq, Dq); | |
| 489 | 14 | if (Lq == 0 || Lk == 0 || Dq == 0) return; | |
| 490 | |||
| 491 | 28 | attention_core(Q.host_f32(), K.host_f32(), V.host_f32(), d_mask, | |
| 492 | 14 | Lq, Lk, Dq, num_q_heads, causal, O.host_f32_mut(), | |
| 493 | 14 | /*P=*/nullptr, /*window=*/0, /*q_offset=*/0, Dkv, | |
| 494 | 14 | /*group=*/num_q_heads / num_kv_heads); | |
| 495 | 14 | } | |
| 496 | |||
| 497 | // ─── flash_attention_varlen_forward ──────────────────────────────────────── | ||
| 498 | // | ||
| 499 | // Packed variable-length attention (Qwen3-VL window attention). Q/K/V are one | ||
| 500 | // big (total_tokens, num_heads*head_dim) tensor each; cu_seqlens_q/k are | ||
| 501 | // length B+1 INT32 prefix sums delimiting per-sequence row ranges. Sequence b | ||
| 502 | // runs attention_core over its own Q[Lq_b, D] and K/V[Lk_b, D] slice — no | ||
| 503 | // cross-sequence attention. | ||
| 504 | // | ||
| 505 | // On CPU cu_seqlens_q/k are raw host pointers (matches the existing d_mask | ||
| 506 | // convention: device pointer on GPU, host pointer on CPU). max_seqlen_q/k are | ||
| 507 | // only used by the GPU kernel for block sizing and are ignored here. | ||
| 508 | 34 | void flash_attention_varlen_forward(const ::brotensor::Tensor& Q, | |
| 509 | const ::brotensor::Tensor& K, | ||
| 510 | const ::brotensor::Tensor& V, | ||
| 511 | const int32_t* cu_seqlens_q, | ||
| 512 | const int32_t* cu_seqlens_k, | ||
| 513 | int batch_size, | ||
| 514 | int /*max_seqlen_q*/, | ||
| 515 | int /*max_seqlen_k*/, | ||
| 516 | int num_heads, | ||
| 517 | int head_dim, | ||
| 518 | bool causal, | ||
| 519 | ::brotensor::Tensor& O) { | ||
| 520 | 34 | const int total_q = Q.rows; | |
| 521 | 34 | const int total_k = K.rows; | |
| 522 | 34 | const int D = num_heads * head_dim; | |
| 523 | 34 | if (Q.cols != D || K.cols != D || V.cols != D || V.rows != total_k) | |
| 524 | ✗ | throw std::runtime_error("flash_attention_varlen_forward: shape mismatch"); | |
| 525 | 34 | if (num_heads <= 0 || head_dim <= 0) | |
| 526 | ✗ | throw std::runtime_error("flash_attention_varlen_forward: num_heads/head_dim must be positive"); | |
| 527 | 34 | if (batch_size < 0) | |
| 528 | ✗ | throw std::runtime_error("flash_attention_varlen_forward: batch_size must be non-negative"); | |
| 529 | 34 | if (batch_size > 0 && (!cu_seqlens_q || !cu_seqlens_k)) | |
| 530 | ✗ | throw std::runtime_error("flash_attention_varlen_forward: cu_seqlens_q/k required when batch_size > 0"); | |
| 531 | 34 | ensure_f32(O, total_q, D); | |
| 532 | 34 | if (total_q == 0 || D == 0) return; | |
| 533 | 34 | if (cu_seqlens_q && cu_seqlens_q[0] != 0) | |
| 534 | ✗ | throw std::runtime_error("flash_attention_varlen_forward: cu_seqlens_q[0] must be 0"); | |
| 535 | 34 | if (cu_seqlens_k && cu_seqlens_k[0] != 0) | |
| 536 | ✗ | throw std::runtime_error("flash_attention_varlen_forward: cu_seqlens_k[0] must be 0"); | |
| 537 | 34 | if (batch_size > 0) { | |
| 538 | 34 | if (cu_seqlens_q[batch_size] != total_q) | |
| 539 | ✗ | throw std::runtime_error("flash_attention_varlen_forward: cu_seqlens_q[B] != total_tokens_q"); | |
| 540 | 34 | if (cu_seqlens_k[batch_size] != total_k) | |
| 541 | ✗ | throw std::runtime_error("flash_attention_varlen_forward: cu_seqlens_k[B] != total_tokens_k"); | |
| 542 | 34 | } | |
| 543 | |||
| 544 | 34 | const float* Qp = Q.host_f32(); | |
| 545 | 34 | const float* Kp = K.host_f32(); | |
| 546 | 34 | const float* Vp = V.host_f32(); | |
| 547 | 34 | float* Op = O.host_f32_mut(); | |
| 548 | |||
| 549 | // Hoist attention_core's per-call `scores` scratch (size Lk) to one | ||
| 550 | // buffer sized for the widest sequence in the batch, reused for every | ||
| 551 | // sequence below — batches of many short sequences would otherwise pay | ||
| 552 | // one small heap allocation per sequence. Negative per-sequence lengths | ||
| 553 | // (malformed cu_seqlens) are skipped here; the loop below throws on them | ||
| 554 | // before attention_core is ever called for that b. | ||
| 555 | 34 | int max_lk = 0; | |
| 556 | 115 | for (int b = 0; b < batch_size; ++b) { | |
| 557 | 81 | const int lk = cu_seqlens_k[b + 1] - cu_seqlens_k[b]; | |
| 558 | 81 | if (lk > max_lk) max_lk = lk; | |
| 559 | 81 | } | |
| 560 | 34 | std::vector<float> scratch_scores(static_cast<std::size_t>(max_lk)); | |
| 561 | |||
| 562 | 115 | for (int b = 0; b < batch_size; ++b) { | |
| 563 | 81 | const int q_beg = cu_seqlens_q[b]; | |
| 564 | 81 | const int q_end = cu_seqlens_q[b + 1]; | |
| 565 | 81 | const int k_beg = cu_seqlens_k[b]; | |
| 566 | 81 | const int k_end = cu_seqlens_k[b + 1]; | |
| 567 | 81 | const int Lq = q_end - q_beg; | |
| 568 | 81 | const int Lk = k_end - k_beg; | |
| 569 | 81 | if (Lq < 0 || Lk < 0) | |
| 570 | ✗ | throw std::runtime_error("flash_attention_varlen_forward: cu_seqlens must be non-decreasing"); | |
| 571 | 81 | if (causal && Lq != Lk) | |
| 572 | ✗ | throw std::runtime_error("flash_attention_varlen_forward: causal requires per-sequence Lq == Lk"); | |
| 573 | 81 | if (Lq == 0) continue; | |
| 574 | 81 | if (Lk == 0) { | |
| 575 | // Fully empty K range — output rows are zero (no keys to attend to). | ||
| 576 | ✗ | for (std::size_t i = 0; i < static_cast<std::size_t>(Lq) * D; ++i) | |
| 577 | ✗ | Op[static_cast<std::size_t>(q_beg) * D + i] = 0.0f; | |
| 578 | ✗ | continue; | |
| 579 | } | ||
| 580 | 162 | attention_core(Qp + static_cast<std::size_t>(q_beg) * D, | |
| 581 | 81 | Kp + static_cast<std::size_t>(k_beg) * D, | |
| 582 | 81 | Vp + static_cast<std::size_t>(k_beg) * D, | |
| 583 | /*mask=*/nullptr, | ||
| 584 | 81 | Lq, Lk, D, num_heads, causal, | |
| 585 | 81 | Op + static_cast<std::size_t>(q_beg) * D, | |
| 586 | /*P=*/nullptr, /*window=*/0, /*q_offset=*/0, /*Dkv=*/-1, | ||
| 587 | 81 | /*group=*/1, scratch_scores.data()); | |
| 588 | 81 | } | |
| 589 | 34 | } | |
| 590 | |||
| 591 | // ─── flash_attention_project_kv ──────────────────────────────────────────── | ||
| 592 | |||
| 593 | 4 | void flash_attention_project_kv(const ::brotensor::Tensor& ctx, | |
| 594 | const ::brotensor::Tensor& Wk, | ||
| 595 | const ::brotensor::Tensor* bk, | ||
| 596 | const ::brotensor::Tensor& Wv, | ||
| 597 | const ::brotensor::Tensor* bv, | ||
| 598 | ::brotensor::Tensor& K_out, | ||
| 599 | ::brotensor::Tensor& V_out) { | ||
| 600 | 4 | const int Lk = ctx.rows; | |
| 601 | 4 | const int D_ctx = ctx.cols; | |
| 602 | 4 | const int D = Wk.rows; | |
| 603 | 4 | if (Wk.cols != D_ctx || Wv.rows != D || Wv.cols != D_ctx) | |
| 604 | ✗ | throw std::runtime_error("flash_attention_project_kv: Wk/Wv shape mismatch"); | |
| 605 | 4 | ensure_f32(K_out, Lk, D); | |
| 606 | 4 | ensure_f32(V_out, Lk, D); | |
| 607 | 4 | if (Lk == 0 || D == 0) return; | |
| 608 | |||
| 609 | 8 | linear_proj(ctx.host_f32(), Wk.host_f32(), | |
| 610 | 4 | bk ? bk->host_f32() : nullptr, | |
| 611 | 4 | K_out.host_f32_mut(), Lk, D_ctx, D); | |
| 612 | 8 | linear_proj(ctx.host_f32(), Wv.host_f32(), | |
| 613 | 4 | bv ? bv->host_f32() : nullptr, | |
| 614 | 4 | V_out.host_f32_mut(), Lk, D_ctx, D); | |
| 615 | 4 | } | |
| 616 | |||
| 617 | // ─── flash_attention_q_with_kv_cached_forward ────────────────────────────── | ||
| 618 | |||
| 619 | 6 | void flash_attention_q_with_kv_cached_forward(const ::brotensor::Tensor& X, | |
| 620 | const ::brotensor::Tensor& K, | ||
| 621 | const ::brotensor::Tensor& V, | ||
| 622 | const ::brotensor::Tensor& Wq, | ||
| 623 | const ::brotensor::Tensor* bq, | ||
| 624 | const ::brotensor::Tensor& Wo, | ||
| 625 | const ::brotensor::Tensor* bo, | ||
| 626 | const float* d_mask, | ||
| 627 | int num_heads, | ||
| 628 | bool causal, | ||
| 629 | ::brotensor::Tensor& O) { | ||
| 630 | 6 | const int Lq = X.rows; | |
| 631 | 6 | const int D = X.cols; | |
| 632 | 6 | const int Lk = K.rows; | |
| 633 | 6 | if (K.cols != D || V.rows != Lk || V.cols != D) | |
| 634 | ✗ | throw std::runtime_error("flash_attention_q_with_kv_cached_forward: K/V shape mismatch"); | |
| 635 | 6 | if (Wq.rows != D || Wq.cols != D || Wo.rows != D || Wo.cols != D) | |
| 636 | ✗ | throw std::runtime_error("flash_attention_q_with_kv_cached_forward: Wq/Wo shape mismatch"); | |
| 637 | 6 | if (num_heads <= 0 || D % num_heads != 0) | |
| 638 | ✗ | throw std::runtime_error("flash_attention_q_with_kv_cached_forward: num_heads must divide D"); | |
| 639 | 6 | ensure_f32(O, Lq, D); | |
| 640 | 6 | if (Lq == 0 || Lk == 0 || D == 0) return; | |
| 641 | |||
| 642 | 6 | std::vector<float> Qp(static_cast<std::size_t>(Lq) * D); | |
| 643 | 6 | std::vector<float> Op(static_cast<std::size_t>(Lq) * D); | |
| 644 | 6 | linear_proj(X.host_f32(), Wq.host_f32(), bq ? bq->host_f32() : nullptr, | |
| 645 | 6 | Qp.data(), Lq, D, D); | |
| 646 | 6 | attention_core(Qp.data(), K.host_f32(), V.host_f32(), d_mask, | |
| 647 | 6 | Lq, Lk, D, num_heads, causal, Op.data(), nullptr); | |
| 648 | 6 | linear_proj(Op.data(), Wo.host_f32(), bo ? bo->host_f32() : nullptr, | |
| 649 | 6 | O.host_f32_mut(), Lq, D, D); | |
| 650 | 6 | } | |
| 651 | |||
| 652 | // ─── flash_attention_qkvo_forward ────────────────────────────────────────── | ||
| 653 | |||
| 654 | 15 | void flash_attention_qkvo_forward(const ::brotensor::Tensor& X, | |
| 655 | const ::brotensor::Tensor* Ctx, | ||
| 656 | const ::brotensor::Tensor& Wq, | ||
| 657 | const ::brotensor::Tensor* bq, | ||
| 658 | const ::brotensor::Tensor& Wk, | ||
| 659 | const ::brotensor::Tensor* bk, | ||
| 660 | const ::brotensor::Tensor& Wv, | ||
| 661 | const ::brotensor::Tensor* bv, | ||
| 662 | const ::brotensor::Tensor& Wo, | ||
| 663 | const ::brotensor::Tensor* bo, | ||
| 664 | const float* d_mask, | ||
| 665 | int num_heads, | ||
| 666 | bool causal, | ||
| 667 | ::brotensor::Tensor& O) { | ||
| 668 | 15 | const int Lq = X.rows; | |
| 669 | 15 | const int D = X.cols; | |
| 670 | 15 | const Tensor& kv_src = Ctx ? *Ctx : X; | |
| 671 | 15 | const int Lk = kv_src.rows; | |
| 672 | 15 | const int D_ctx = kv_src.cols; | |
| 673 | 30 | if (Wq.rows != D || Wq.cols != D || | |
| 674 | 15 | Wk.rows != D || Wk.cols != D_ctx || | |
| 675 | 15 | Wv.rows != D || Wv.cols != D_ctx || | |
| 676 | 15 | Wo.rows != D || Wo.cols != D) | |
| 677 | ✗ | throw std::runtime_error("flash_attention_qkvo_forward: shape mismatch"); | |
| 678 | 15 | if (num_heads <= 0 || D % num_heads != 0) | |
| 679 | ✗ | throw std::runtime_error("flash_attention_qkvo_forward: num_heads must divide D"); | |
| 680 | 15 | ensure_f32(O, Lq, D); | |
| 681 | 15 | if (Lq == 0 || Lk == 0 || D == 0) return; | |
| 682 | |||
| 683 | 15 | std::vector<float> Qp(static_cast<std::size_t>(Lq) * D); | |
| 684 | 15 | std::vector<float> Kp(static_cast<std::size_t>(Lk) * D); | |
| 685 | 15 | std::vector<float> Vp(static_cast<std::size_t>(Lk) * D); | |
| 686 | 15 | std::vector<float> Op(static_cast<std::size_t>(Lq) * D); | |
| 687 | |||
| 688 | 15 | linear_proj(X.host_f32(), Wq.host_f32(), bq ? bq->host_f32() : nullptr, | |
| 689 | 15 | Qp.data(), Lq, D, D); | |
| 690 | 30 | linear_proj(kv_src.host_f32(), Wk.host_f32(), | |
| 691 | 15 | bk ? bk->host_f32() : nullptr, Kp.data(), Lk, D_ctx, D); | |
| 692 | 30 | linear_proj(kv_src.host_f32(), Wv.host_f32(), | |
| 693 | 15 | bv ? bv->host_f32() : nullptr, Vp.data(), Lk, D_ctx, D); | |
| 694 | 30 | attention_core(Qp.data(), Kp.data(), Vp.data(), d_mask, | |
| 695 | 15 | Lq, Lk, D, num_heads, causal, Op.data(), nullptr); | |
| 696 | 15 | linear_proj(Op.data(), Wo.host_f32(), bo ? bo->host_f32() : nullptr, | |
| 697 | 15 | O.host_f32_mut(), Lq, D, D); | |
| 698 | 15 | } | |
| 699 | |||
| 700 | // ─── flash_attention_backward ────────────────────────────────────────────── | ||
| 701 | |||
| 702 | 9 | void flash_attention_backward(const ::brotensor::Tensor& Q, | |
| 703 | const ::brotensor::Tensor& K, | ||
| 704 | const ::brotensor::Tensor& V, | ||
| 705 | const ::brotensor::Tensor& O, | ||
| 706 | const ::brotensor::Tensor& dO, | ||
| 707 | const float* d_mask, | ||
| 708 | int num_heads, | ||
| 709 | bool causal, | ||
| 710 | ::brotensor::Tensor& dQ, | ||
| 711 | ::brotensor::Tensor& dK, | ||
| 712 | ::brotensor::Tensor& dV) { | ||
| 713 | 9 | (void)O; // recompute-based; O retained in API for symmetry. | |
| 714 | 9 | const int Lq = Q.rows; | |
| 715 | 9 | const int Lk = K.rows; | |
| 716 | 9 | const int D = Q.cols; | |
| 717 | 9 | if (K.cols != D || V.cols != D || V.rows != Lk) | |
| 718 | ✗ | throw std::runtime_error("flash_attention_backward: Q/K/V shape mismatch"); | |
| 719 | 9 | if (dO.rows != Lq || dO.cols != D) | |
| 720 | ✗ | throw std::runtime_error("flash_attention_backward: dO shape mismatch"); | |
| 721 | 9 | if (num_heads <= 0 || D % num_heads != 0) | |
| 722 | ✗ | throw std::runtime_error("flash_attention_backward: num_heads must divide D"); | |
| 723 | 9 | if (causal && Lq != Lk) | |
| 724 | ✗ | throw std::runtime_error("flash_attention_backward: causal requires Lq == Lk"); | |
| 725 | 9 | ensure_f32(dQ, Lq, D); | |
| 726 | 9 | ensure_f32(dK, Lk, D); | |
| 727 | 9 | ensure_f32(dV, Lk, D); | |
| 728 | 9 | if (Lq == 0 || Lk == 0 || D == 0) return; | |
| 729 | |||
| 730 | 18 | attention_core_backward(Q.host_f32(), K.host_f32(), V.host_f32(), | |
| 731 | 9 | dO.host_f32(), d_mask, Lq, Lk, D, num_heads, | |
| 732 | 9 | causal, dQ.host_f32_mut(), dK.host_f32_mut(), | |
| 733 | 9 | dV.host_f32_mut()); | |
| 734 | 9 | } | |
| 735 | |||
| 736 | // ─── flash_attention_varlen_backward ─────────────────────────────────────── | ||
| 737 | // | ||
| 738 | // Per-sequence backward over the packed (total_tokens, D) layout. Same | ||
| 739 | // recompute math as flash_attention_backward (attention_core_backward) run | ||
| 740 | // once per sequence on its [cu_seqlens_q[b], cu_seqlens_q[b+1]) Q slice and | ||
| 741 | // [cu_seqlens_k[b], cu_seqlens_k[b+1]) K/V slice. dQ/dK/dV are OVERWRITTEN — | ||
| 742 | // attention_core_backward zeros its per-call output region, and rows outside | ||
| 743 | // any sequence's range (which can't happen for a well-formed cu_seqlens) plus | ||
| 744 | // rows whose K range is empty are explicitly zeroed here so the contract | ||
| 745 | // holds globally. | ||
| 746 | 24 | void flash_attention_varlen_backward(const ::brotensor::Tensor& Q, | |
| 747 | const ::brotensor::Tensor& K, | ||
| 748 | const ::brotensor::Tensor& V, | ||
| 749 | const ::brotensor::Tensor& O, | ||
| 750 | const ::brotensor::Tensor& dO, | ||
| 751 | const int32_t* cu_seqlens_q, | ||
| 752 | const int32_t* cu_seqlens_k, | ||
| 753 | int batch_size, | ||
| 754 | int /*max_seqlen_q*/, | ||
| 755 | int /*max_seqlen_k*/, | ||
| 756 | int num_heads, | ||
| 757 | int head_dim, | ||
| 758 | bool causal, | ||
| 759 | ::brotensor::Tensor& dQ, | ||
| 760 | ::brotensor::Tensor& dK, | ||
| 761 | ::brotensor::Tensor& dV) { | ||
| 762 | 24 | (void)O; // recompute-based; O retained in API for symmetry. | |
| 763 | 24 | const int total_q = Q.rows; | |
| 764 | 24 | const int total_k = K.rows; | |
| 765 | 24 | const int D = num_heads * head_dim; | |
| 766 | 24 | if (Q.cols != D || K.cols != D || V.cols != D || V.rows != total_k) | |
| 767 | ✗ | throw std::runtime_error("flash_attention_varlen_backward: Q/K/V shape mismatch"); | |
| 768 | 24 | if (dO.rows != total_q || dO.cols != D) | |
| 769 | ✗ | throw std::runtime_error("flash_attention_varlen_backward: dO shape mismatch"); | |
| 770 | 24 | if (num_heads <= 0 || head_dim <= 0) | |
| 771 | ✗ | throw std::runtime_error("flash_attention_varlen_backward: num_heads/head_dim must be positive"); | |
| 772 | 24 | if (batch_size < 0) | |
| 773 | ✗ | throw std::runtime_error("flash_attention_varlen_backward: batch_size must be non-negative"); | |
| 774 | 24 | if (batch_size > 0 && (!cu_seqlens_q || !cu_seqlens_k)) | |
| 775 | ✗ | throw std::runtime_error("flash_attention_varlen_backward: cu_seqlens_q/k required when batch_size > 0"); | |
| 776 | 24 | ensure_f32(dQ, total_q, D); | |
| 777 | 24 | ensure_f32(dK, total_k, D); | |
| 778 | 24 | ensure_f32(dV, total_k, D); | |
| 779 | 24 | if (total_q == 0 && total_k == 0) return; | |
| 780 | 24 | if (D == 0) return; | |
| 781 | 24 | if (cu_seqlens_q && cu_seqlens_q[0] != 0) | |
| 782 | ✗ | throw std::runtime_error("flash_attention_varlen_backward: cu_seqlens_q[0] must be 0"); | |
| 783 | 24 | if (cu_seqlens_k && cu_seqlens_k[0] != 0) | |
| 784 | ✗ | throw std::runtime_error("flash_attention_varlen_backward: cu_seqlens_k[0] must be 0"); | |
| 785 | 24 | if (batch_size > 0) { | |
| 786 | 24 | if (cu_seqlens_q[batch_size] != total_q) | |
| 787 | ✗ | throw std::runtime_error("flash_attention_varlen_backward: cu_seqlens_q[B] != total_tokens_q"); | |
| 788 | 24 | if (cu_seqlens_k[batch_size] != total_k) | |
| 789 | ✗ | throw std::runtime_error("flash_attention_varlen_backward: cu_seqlens_k[B] != total_tokens_k"); | |
| 790 | 24 | } | |
| 791 | |||
| 792 | // Zero all grads upfront so any rows not covered by a sequence (or covered | ||
| 793 | // by an empty-K sequence) end up at exactly 0.0f without depending on the | ||
| 794 | // per-sequence path to touch them. | ||
| 795 | 24 | float* dQp = dQ.host_f32_mut(); | |
| 796 | 24 | float* dKp = dK.host_f32_mut(); | |
| 797 | 24 | float* dVp = dV.host_f32_mut(); | |
| 798 | 8736 | for (std::size_t i = 0; i < static_cast<std::size_t>(total_q) * D; ++i) dQp[i] = 0.0f; | |
| 799 | 8992 | for (std::size_t i = 0; i < static_cast<std::size_t>(total_k) * D; ++i) { | |
| 800 | 8968 | dKp[i] = 0.0f; | |
| 801 | 8968 | dVp[i] = 0.0f; | |
| 802 | 8968 | } | |
| 803 | 24 | if (batch_size == 0) return; | |
| 804 | |||
| 805 | 24 | const float* Qp = Q.host_f32(); | |
| 806 | 24 | const float* Kp = K.host_f32(); | |
| 807 | 24 | const float* Vp = V.host_f32(); | |
| 808 | 24 | const float* dOp = dO.host_f32(); | |
| 809 | |||
| 810 | // Hoist attention_core_backward's per-call P/dP/dS scratch (each size | ||
| 811 | // Lq*Lk) to one triple of buffers sized for the widest sequence in the | ||
| 812 | // batch, reused for every sequence below — batches of many short | ||
| 813 | // sequences would otherwise pay three small heap allocations per | ||
| 814 | // sequence. Malformed (negative) per-sequence lengths are skipped in this | ||
| 815 | // sizing pass; the loop below throws on them before attention_core_backward | ||
| 816 | // is ever called for that b, and casting a negative length to size_t here | ||
| 817 | // could otherwise wrap to a huge value and provoke a bogus allocation. | ||
| 818 | 24 | std::size_t max_qk = 0; | |
| 819 | 71 | for (int b = 0; b < batch_size; ++b) { | |
| 820 | 47 | const int lq = cu_seqlens_q[b + 1] - cu_seqlens_q[b]; | |
| 821 | 47 | const int lk = cu_seqlens_k[b + 1] - cu_seqlens_k[b]; | |
| 822 | 47 | if (lq < 0 || lk < 0) continue; | |
| 823 | 47 | const std::size_t qk = | |
| 824 | 47 | static_cast<std::size_t>(lq) * static_cast<std::size_t>(lk); | |
| 825 | 47 | if (qk > max_qk) max_qk = qk; | |
| 826 | 47 | } | |
| 827 | 24 | std::vector<float> scratch_P(max_qk); | |
| 828 | 24 | std::vector<float> scratch_dP(max_qk); | |
| 829 | 24 | std::vector<float> scratch_dS(max_qk); | |
| 830 | |||
| 831 | 71 | for (int b = 0; b < batch_size; ++b) { | |
| 832 | 47 | const int q_beg = cu_seqlens_q[b]; | |
| 833 | 47 | const int q_end = cu_seqlens_q[b + 1]; | |
| 834 | 47 | const int k_beg = cu_seqlens_k[b]; | |
| 835 | 47 | const int k_end = cu_seqlens_k[b + 1]; | |
| 836 | 47 | const int Lq = q_end - q_beg; | |
| 837 | 47 | const int Lk = k_end - k_beg; | |
| 838 | 47 | if (Lq < 0 || Lk < 0) | |
| 839 | ✗ | throw std::runtime_error("flash_attention_varlen_backward: cu_seqlens must be non-decreasing"); | |
| 840 | 47 | if (causal && Lq != Lk) | |
| 841 | ✗ | throw std::runtime_error("flash_attention_varlen_backward: causal requires per-sequence Lq == Lk"); | |
| 842 | 47 | if (Lq == 0 || Lk == 0) continue; // grad rows already zero. | |
| 843 | |||
| 844 | 46 | attention_core_backward( | |
| 845 | 46 | Qp + static_cast<std::size_t>(q_beg) * D, | |
| 846 | 46 | Kp + static_cast<std::size_t>(k_beg) * D, | |
| 847 | 46 | Vp + static_cast<std::size_t>(k_beg) * D, | |
| 848 | 46 | dOp + static_cast<std::size_t>(q_beg) * D, | |
| 849 | /*mask=*/nullptr, | ||
| 850 | 46 | Lq, Lk, D, num_heads, causal, | |
| 851 | 46 | dQp + static_cast<std::size_t>(q_beg) * D, | |
| 852 | 46 | dKp + static_cast<std::size_t>(k_beg) * D, | |
| 853 | 46 | dVp + static_cast<std::size_t>(k_beg) * D, | |
| 854 | 46 | scratch_P.data(), scratch_dP.data(), scratch_dS.data()); | |
| 855 | 46 | } | |
| 856 | 24 | } | |
| 857 | |||
| 858 | // ─── flash_attention_qkvo_backward ───────────────────────────────────────── | ||
| 859 | |||
| 860 | 9 | void flash_attention_qkvo_backward(const ::brotensor::Tensor& X, | |
| 861 | const ::brotensor::Tensor* Ctx, | ||
| 862 | const ::brotensor::Tensor& Wq, | ||
| 863 | const ::brotensor::Tensor* bq, | ||
| 864 | const ::brotensor::Tensor& Wk, | ||
| 865 | const ::brotensor::Tensor* bk, | ||
| 866 | const ::brotensor::Tensor& Wv, | ||
| 867 | const ::brotensor::Tensor* bv, | ||
| 868 | const ::brotensor::Tensor& Wo, | ||
| 869 | const ::brotensor::Tensor* bo, | ||
| 870 | const float* d_mask, | ||
| 871 | int num_heads, | ||
| 872 | bool causal, | ||
| 873 | const ::brotensor::Tensor& dO, | ||
| 874 | ::brotensor::Tensor& dX, | ||
| 875 | ::brotensor::Tensor* dCtx, | ||
| 876 | ::brotensor::Tensor& dWq, | ||
| 877 | ::brotensor::Tensor* dbq, | ||
| 878 | ::brotensor::Tensor& dWk, | ||
| 879 | ::brotensor::Tensor* dbk, | ||
| 880 | ::brotensor::Tensor& dWv, | ||
| 881 | ::brotensor::Tensor* dbv, | ||
| 882 | ::brotensor::Tensor& dWo, | ||
| 883 | ::brotensor::Tensor* dbo) { | ||
| 884 | 9 | const bool self_attn = (Ctx == nullptr); | |
| 885 | 9 | if (self_attn && dCtx != nullptr) | |
| 886 | ✗ | throw std::runtime_error("flash_attention_qkvo_backward: dCtx must be null when Ctx is null"); | |
| 887 | 9 | if (!self_attn && dCtx == nullptr) | |
| 888 | ✗ | throw std::runtime_error("flash_attention_qkvo_backward: dCtx must be non-null when Ctx is non-null"); | |
| 889 | 45 | auto bias_ok = [](const Tensor* b, const Tensor* db) { | |
| 890 | 36 | return static_cast<bool>(b) == static_cast<bool>(db); | |
| 891 | }; | ||
| 892 | 18 | if (!bias_ok(bq, dbq) || !bias_ok(bk, dbk) || | |
| 893 | 9 | !bias_ok(bv, dbv) || !bias_ok(bo, dbo)) | |
| 894 | ✗ | throw std::runtime_error("flash_attention_qkvo_backward: bias/grad-bias presence mismatch"); | |
| 895 | |||
| 896 | 9 | const int Lq = X.rows; | |
| 897 | 9 | const int D = X.cols; | |
| 898 | 9 | const Tensor& kv_src = Ctx ? *Ctx : X; | |
| 899 | 9 | const int Lk = kv_src.rows; | |
| 900 | 9 | const int D_ctx = kv_src.cols; | |
| 901 | 18 | if (Wq.rows != D || Wq.cols != D || | |
| 902 | 9 | Wk.rows != D || Wk.cols != D_ctx || | |
| 903 | 9 | Wv.rows != D || Wv.cols != D_ctx || | |
| 904 | 9 | Wo.rows != D || Wo.cols != D) | |
| 905 | ✗ | throw std::runtime_error("flash_attention_qkvo_backward: shape mismatch"); | |
| 906 | 9 | if (dO.rows != Lq || dO.cols != D) | |
| 907 | ✗ | throw std::runtime_error("flash_attention_qkvo_backward: dO shape mismatch"); | |
| 908 | 9 | if (num_heads <= 0 || D % num_heads != 0) | |
| 909 | ✗ | throw std::runtime_error("flash_attention_qkvo_backward: num_heads must divide D"); | |
| 910 | 9 | if (causal && Lq != Lk) | |
| 911 | ✗ | throw std::runtime_error("flash_attention_qkvo_backward: causal requires Lq == Lk"); | |
| 912 | |||
| 913 | 9 | ensure_f32(dX, Lq, D); | |
| 914 | 9 | dX.zero(); | |
| 915 | 9 | if (!self_attn) { | |
| 916 | 3 | ensure_f32(*dCtx, Lk, D_ctx); | |
| 917 | 3 | dCtx->zero(); | |
| 918 | 3 | } | |
| 919 | 9 | if (Lq == 0 || Lk == 0 || D == 0) return; | |
| 920 | |||
| 921 | 9 | const float* Xp = X.host_f32(); | |
| 922 | 9 | const float* kvp = kv_src.host_f32(); | |
| 923 | |||
| 924 | // ── 1. Recompute forward projections. ── | ||
| 925 | 9 | std::vector<float> Q(static_cast<std::size_t>(Lq) * D); | |
| 926 | 9 | std::vector<float> K(static_cast<std::size_t>(Lk) * D); | |
| 927 | 9 | std::vector<float> V(static_cast<std::size_t>(Lk) * D); | |
| 928 | 9 | linear_proj(Xp, Wq.host_f32(), bq ? bq->host_f32() : nullptr, | |
| 929 | 9 | Q.data(), Lq, D, D); | |
| 930 | 9 | linear_proj(kvp, Wk.host_f32(), bk ? bk->host_f32() : nullptr, | |
| 931 | 9 | K.data(), Lk, D_ctx, D); | |
| 932 | 9 | linear_proj(kvp, Wv.host_f32(), bv ? bv->host_f32() : nullptr, | |
| 933 | 9 | V.data(), Lk, D_ctx, D); | |
| 934 | |||
| 935 | // ── 2. Recompute O_attn (post-attention, pre-Wo). ── | ||
| 936 | 9 | std::vector<float> O_attn(static_cast<std::size_t>(Lq) * D); | |
| 937 | 18 | attention_core(Q.data(), K.data(), V.data(), d_mask, | |
| 938 | 9 | Lq, Lk, D, num_heads, causal, O_attn.data(), nullptr); | |
| 939 | |||
| 940 | // ── 3. Wo backward: dO_attn = dO·Wo, dWo += dO^T·O_attn, dbo += colsum. ── | ||
| 941 | 9 | std::vector<float> dO_attn(static_cast<std::size_t>(Lq) * D, 0.0f); | |
| 942 | 18 | linear_proj_backward(O_attn.data(), Wo.host_f32(), dO.host_f32(), | |
| 943 | 9 | dO_attn.data(), dWo.host_f32_mut(), | |
| 944 | 9 | dbo ? dbo->host_f32_mut() : nullptr, | |
| 945 | 9 | Lq, D, D); | |
| 946 | |||
| 947 | // ── 4. Attention core backward → dQ, dK, dV. ── | ||
| 948 | 9 | std::vector<float> dQ(static_cast<std::size_t>(Lq) * D); | |
| 949 | 9 | std::vector<float> dK(static_cast<std::size_t>(Lk) * D); | |
| 950 | 9 | std::vector<float> dV(static_cast<std::size_t>(Lk) * D); | |
| 951 | 18 | attention_core_backward(Q.data(), K.data(), V.data(), dO_attn.data(), | |
| 952 | 9 | d_mask, Lq, Lk, D, num_heads, causal, | |
| 953 | 9 | dQ.data(), dK.data(), dV.data()); | |
| 954 | |||
| 955 | // ── 5. Q/K/V projection backward. ── | ||
| 956 | // dX accumulates the Q path (and, for self-attn, the K and V paths). | ||
| 957 | // dWq/dWk/dWv and dbq/dbk/dbv accumulate. | ||
| 958 | 9 | float* dXp = dX.host_f32_mut(); | |
| 959 | 18 | linear_proj_backward(Xp, Wq.host_f32(), dQ.data(), dXp, | |
| 960 | 9 | dWq.host_f32_mut(), | |
| 961 | 9 | dbq ? dbq->host_f32_mut() : nullptr, | |
| 962 | 9 | Lq, D, D); | |
| 963 | 9 | if (self_attn) { | |
| 964 | 12 | linear_proj_backward(Xp, Wk.host_f32(), dK.data(), dXp, | |
| 965 | 6 | dWk.host_f32_mut(), | |
| 966 | 6 | dbk ? dbk->host_f32_mut() : nullptr, | |
| 967 | 6 | Lk, D_ctx, D); | |
| 968 | 12 | linear_proj_backward(Xp, Wv.host_f32(), dV.data(), dXp, | |
| 969 | 6 | dWv.host_f32_mut(), | |
| 970 | 6 | dbv ? dbv->host_f32_mut() : nullptr, | |
| 971 | 6 | Lk, D_ctx, D); | |
| 972 | 6 | } else { | |
| 973 | 3 | float* dCp = dCtx->host_f32_mut(); | |
| 974 | 6 | linear_proj_backward(kvp, Wk.host_f32(), dK.data(), dCp, | |
| 975 | 3 | dWk.host_f32_mut(), | |
| 976 | 3 | dbk ? dbk->host_f32_mut() : nullptr, | |
| 977 | 3 | Lk, D_ctx, D); | |
| 978 | 6 | linear_proj_backward(kvp, Wv.host_f32(), dV.data(), dCp, | |
| 979 | 3 | dWv.host_f32_mut(), | |
| 980 | 3 | dbv ? dbv->host_f32_mut() : nullptr, | |
| 981 | 3 | Lk, D_ctx, D); | |
| 982 | } | ||
| 983 | 9 | } | |
| 984 | |||
| 985 | } // namespace brotensor::detail::cpu | ||
| 986 |