/* xe2_attn_fast.cpp -- Phase 4's paged attention: split-KV with an online softmax ("flash * decoding"), a kv head's keys read once for all its query heads. * * Pass 1: a work-group a (query row, kv head, key partition). Its sub-groups are the kv head's * query heads (sub-group s takes heads s, s + 8, ...); each walks the partition's visible keys in * order, its lanes splitting head_dim, so a key's score is a sub-group reduction of * q . (k * k_descale), scaled, and the sub-group keeps the flash state: max m, sum l and its lanes' * slice of the weighted value sum, rescaled by exp(m_old - m_new) as the max grows. The eight query * heads read the same key and value rows, so the bytes come from memory once a work-group. * * The partition count P is chosen at launch from the rows: a decode step (one row, a few heads) * splits the keys into partitions of 32 or more so the whole card works on one token; a * prefill step has parallelism in its rows and takes P = 1. With P > 1 each partition's state goes * to scratch (64 MiB, the `scratch` hook) and pass 2 -- a sub-group a (row, query head) -- merges * them; with P = 1 pass 1 writes the normalised output itself. * * Same mask, window, ragged batches (cu_seqlens), fp8 descales and zero row for no visible key as * libref's attn_paged and xe2_attn_paged_ref. Not libref's order: held to rad-kbench's attention * tolerance and the KL bound (D13). XE2_EXACT=1, a head_dim that is not a multiple of 16 up to 256, * or a rank-3 cache, sends the launch to xe2_attn_paged_ref. */ #include "xe2_common.h" #include "xe2_ops.h" #include namespace xe2 { namespace { constexpr int kSgs = 8; constexpr size_t kWg = kSgs * kSub; constexpr int kMaxPer = 16; /* head_dim / 16, up to head_dim 256 */ constexpr int64_t kScratch = (int64_t)64 << 20; /* pass 1's partial states */ constexpr int64_t kPartKeys = 32; /* the finest partition */ constexpr int64_t kMaxParts = 1024; int64_t row_stride(const RadTensor* t, int64_t cols) { if (!t || t->rank < 2) return cols; int64_t span = 1; for (int i = (int)t->rank - 1; i >= 0; --i) { span *= t->shape[i]; if (span == cols) return (i > 0) ? t->stride[i - 1] : cols; if (span > cols) break; } return t->stride[t->rank - 2]; } } // namespace int64_t attn_paged_scratch(const RadArgs*) { return kScratch; } int attn_paged_fast(const RadArgs* a, RadStream st) { if (exact_only()) return attn_paged(a, st); if (!a || a->n_t < 8) return RAD_E_INVAL; const RadTensor *Q = &a->t[0], *KV = &a->t[1], *BT = &a->t[2], *SU = &a->t[3], *O = &a->t[7]; const RadTensor* KD = rad_arg_in(a, 4); const RadTensor* VD = rad_arg_in(a, 5); const RadTensor* CU = rad_arg_in(a, 6); if (!Q->data || !KV->data || !BT->data || !SU->data || !O->data) return RAD_E_INVAL; const int64_t head_dim = rad_args_geti_or(a, "head_dim", Q->rank >= 3 ? Q->shape[Q->rank - 1] : 0); if (head_dim <= 0 || head_dim % kSub || head_dim / kSub > kMaxPer || KV->rank != 4) return attn_paged(a, st); const int64_t gqa = rad_args_geti_or(a, "gqa", 1); const int64_t block_size = rad_args_geti_or(a, "block_size", KV->shape[2]); const int causal = (int)rad_args_geti_or(a, "causal", 1); const int64_t window = rad_args_geti_or(a, "window", 0); if (gqa <= 0 || block_size <= 0) return RAD_E_SHAPE; const int64_t kv_heads = KV->shape[1]; if (kv_heads <= 0) return RAD_E_SHAPE; const int64_t q_heads = gqa * kv_heads; if (Q->rank >= 3 && Q->shape[Q->rank - 2] != q_heads) return RAD_E_SHAPE; const int64_t n_seq = rad_tensor_numel(SU); const int64_t rows = rad_tensor_numel(Q) / (q_heads * head_dim); if (n_seq <= 0 || rows <= 0) return RAD_E_SHAPE; if (!CU && rows % n_seq != 0) return RAD_E_SHAPE; if (CU && rad_tensor_numel(CU) != n_seq + 1) return RAD_E_SHAPE; const int64_t q_len_all = CU ? 0 : rows / n_seq; if (rad_tensor_numel(O) < rows * q_heads * head_dim) return RAD_E_SHAPE; if (KV->shape[2] != block_size || KV->shape[3] < 2 * head_dim) return RAD_E_SHAPE; if (!rad_tensor_is_contiguous(SU) || (CU && !rad_tensor_is_contiguous(CU)) || (KD && !rad_tensor_is_contiguous(KD)) || (VD && !rad_tensor_is_contiguous(VD))) return attn_paged(a, st); const int64_t max_blocks = BT->rank >= 2 ? BT->shape[BT->rank - 1] : rad_tensor_numel(BT) / n_seq; const int64_t bt_rs = BT->rank >= 2 ? BT->stride[BT->rank - 2] : max_blocks; const int64_t bt_cs = BT->rank >= 2 ? BT->stride[BT->rank - 1] : 1; const int64_t sb = KV->stride[0], sh = KV->stride[1], so = KV->stride[2], sd = KV->stride[3]; const int64_t q_ds = Q->rank >= 2 ? Q->stride[Q->rank - 1] : 1; const int64_t q_hs = Q->rank >= 3 ? Q->stride[Q->rank - 2] : head_dim * q_ds; const int64_t q_rs = row_stride(Q, q_heads * head_dim); const int64_t o_ds = O->rank >= 2 ? O->stride[O->rank - 1] : 1; const int64_t o_hs = O->rank >= 3 ? O->stride[O->rank - 2] : head_dim * o_ds; const int64_t o_rs = row_stride(O, q_heads * head_dim); const float scale = (float)rad_args_getf_or(a, "scale", (double)(1.0f / std::sqrt((float)head_dim))); const int64_t jcap = max_blocks * block_size; const int per = (int)(head_dim / kSub); /* The partitions: as many as the scratch holds for these rows, none finer than kPartKeys. */ const int64_t state = 2 + head_dim; /* floats a partial state: m, l, acc[head_dim] */ int64_t P = 1; if (a->scratch && a->scratch_bytes > 0) { const int64_t fit = a->scratch_bytes / (rows * q_heads * state * (int64_t)sizeof(float)); P = sycl::min(sycl::min(fit, kMaxParts), (jcap + kPartKeys - 1) / kPartKeys); if (P < 1) P = 1; } const int64_t chunk = (jcap + P - 1) / P; float* part = (float*)a->scratch; const char *qb = (const char*)Q->data, *cb = (const char*)KV->data, *btb = (const char*)BT->data; const char *sub = (const char*)SU->data, *cub = CU ? (const char*)CU->data : nullptr; const char *kdb = KD ? (const char*)KD->data : nullptr, *vdb = VD ? (const char*)VD->data : nullptr; char* ob = (char*)O->data; const uint32_t qdt = Q->dtype, cdt = KV->dtype, btdt = BT->dtype, sudt = SU->dtype; const uint32_t cudt = CU ? CU->dtype : 0, kddt = KD ? KD->dtype : 0, vddt = VD ? VD->dtype : 0; const uint32_t odt = O->dtype; sycl::queue* q = queue_of(st); if (!q) return RAD_E_DEVICE; int rc = submit([&] { syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)(rows * kv_heads * P) * kWg, kWg}, [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] { const int64_t g = (int64_t)it.get_group(0); const int64_t p = g % P, kh = (g / P) % kv_heads, tok = g / (P * kv_heads); const sycl::sub_group sg = it.get_sub_group(); const int s = (int)sg.get_group_linear_id(); const int lane = (int)sg.get_local_linear_id(); int64_t sq = 0, qlen = q_len_all, i = 0; if (cub) { while (sq + 1 < n_seq && ld_index(cudt, cub, sq + 1) <= tok) ++sq; qlen = ld_index(cudt, cub, sq + 1) - ld_index(cudt, cub, sq); i = tok - ld_index(cudt, cub, sq); } else { sq = tok / q_len_all; i = tok - sq * q_len_all; } if (qlen <= 0) return; const int64_t ctx = ld_index(sudt, sub, sq); const int64_t pos = ctx - qlen + i; const float kds = kdb ? rad_load_f32(kdb, kddt, sq * kv_heads + kh) : 1.0f; const float vds = vdb ? rad_load_f32(vdb, vddt, sq * kv_heads + kh) : 1.0f; const int64_t jend = sycl::min(ctx, jcap); int64_t jlo = 0, jhi = causal ? sycl::min(jend, pos + 1) : jend; if (window > 0) { jlo = sycl::max((int64_t)0, pos - window + 1); if (!causal) jhi = sycl::min(jend, pos + window); } jlo = sycl::max(jlo, p * chunk); jhi = sycl::min(jhi, (p + 1) * chunk); for (int64_t hl = s; hl < gqa; hl += kSgs) { const int64_t hq = kh * gqa + hl; const int64_t qoff = tok * q_rs + hq * q_hs; float qv[kMaxPer], acc[kMaxPer]; for (int e = 0; e < kMaxPer; ++e) { qv[e] = e < per ? rad_load_f32(qb, qdt, qoff + (lane * per + e) * q_ds) : 0.0f; acc[e] = 0.0f; } float m = -INFINITY, l = 0.0f; for (int64_t j = jlo; j < jhi; ++j) { const int64_t blk = ld_index(btdt, btb, sq * bt_rs + (j / block_size) * bt_cs); if (blk < 0) continue; const int64_t kb = blk * sb + kh * sh + (j % block_size) * so; float pp = 0.0f; for (int e = 0; e < per; ++e) pp += qv[e] * (rad_load_f32(cb, cdt, kb + (lane * per + e) * sd) * kds); const float sc = sycl::reduce_over_group(sg, pp, sycl::plus()) * scale; const float mn = sycl::fmax(m, sc); const float corr = sycl::exp(m - mn), w = sycl::exp(sc - mn); l = l * corr + w; for (int e = 0; e < per; ++e) acc[e] = acc[e] * corr + w * (rad_load_f32(cb, cdt, kb + (head_dim + lane * per + e) * sd) * vds); m = mn; } if (P == 1) { const int64_t ooff = tok * o_rs + hq * o_hs; const float inv = l > 0.0f ? 1.0f / l : 0.0f; /* no visible key: zero row */ for (int e = 0; e < per; ++e) rad_store_f32(ob, odt, ooff + (lane * per + e) * o_ds, acc[e] * inv); } else { float* ps = part + ((tok * q_heads + hq) * P + p) * state; if (lane == 0) { ps[0] = m; ps[1] = l; } for (int e = 0; e < per; ++e) ps[2 + lane * per + e] = acc[e]; } } }); }); if (rc < 0 || P == 1) return rc; /* Pass 2: merge the partitions of each (row, query head). */ return submit([&] { syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)(rows * q_heads) * kSub, (size_t)kSub}, [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] { const int64_t g = (int64_t)it.get_group(0); const int64_t hq = g % q_heads, tok = g / q_heads; const int lane = (int)it.get_local_id(0); int64_t sq = 0, qlen = q_len_all; if (cub) { while (sq + 1 < n_seq && ld_index(cudt, cub, sq + 1) <= tok) ++sq; qlen = ld_index(cudt, cub, sq + 1) - ld_index(cudt, cub, sq); } if (qlen <= 0) return; const float* ps = part + (tok * q_heads + hq) * P * state; float M = -INFINITY; for (int64_t p = 0; p < P; ++p) if (ps[p * state + 1] > 0.0f) M = sycl::fmax(M, ps[p * state]); const int64_t ooff = tok * o_rs + hq * o_hs; float L = 0.0f, out[kMaxPer]; for (int e = 0; e < kMaxPer; ++e) out[e] = 0.0f; if (M != -INFINITY) for (int64_t p = 0; p < P; ++p) { const float* q0 = ps + p * state; if (!(q0[1] > 0.0f)) continue; /* an empty partition */ const float f = sycl::exp(q0[0] - M); L += q0[1] * f; for (int e = 0; e < per; ++e) out[e] += q0[2 + lane * per + e] * f; } const float inv = L > 0.0f ? 1.0f / L : 0.0f; for (int e = 0; e < per; ++e) rad_store_f32(ob, odt, ooff + (lane * per + e) * o_ds, out[e] * inv); }); }); } } // namespace xe2