/* xe2_attn_fast.cpp -- Phase 4's paged attention: one pass over the keys with an online softmax, * the keys spread over the work-group, for decode and prefill alike. * * One work-group a (query row, head), eight 16-lane sub-groups. Sub-group s takes keys s, s + 8, * s + 16, ... of the row's visible span; its lanes split head_dim (head_dim / 16 elements each), so * a key's score is a sub-group reduction of q . (k * k_descale), scaled. Each sub-group keeps the * flash-attention running state -- max m, sum l, and its lanes' slice of the weighted value sum -- * rescaling by exp(m_old - m_new) as the max grows; at the end the eight states are merged through * local memory and lane d's slice is divided by the merged sum. * * 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 (it takes the max first and sums * in key order): held to rad-kbench's attention tolerance and the KL bound (D13). XE2_EXACT=1, or a * head_dim that is not a multiple of 16 up to 256, 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 */ 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 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) 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->rank == 4 ? KV->shape[2] : 0); 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->rank == 4 ? KV->shape[1] : 0; if (kv_heads <= 0 || KV->rank != 4) 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); 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; const int64_t total = rows * q_heads; sycl::queue* q = queue_of(st); if (!q) return RAD_E_DEVICE; return submit([&] { q->submit([&](sycl::handler& h) { /* Each sub-group's final state: m, l, and its head_dim-wide accumulator. */ sycl::local_accessor sm(sycl::range<1>(kSgs), h); sycl::local_accessor sl(sycl::range<1>(kSgs), h); sycl::local_accessor sacc(sycl::range<1>((size_t)kSgs * kSub * kMaxPer), h); h.parallel_for(sycl::nd_range<1>{(size_t)total * kWg, kWg}, [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] { const int64_t idx = (int64_t)it.get_group(0); 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(); const int64_t hq = idx % q_heads, tok = idx / q_heads; 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; /* uniform across the group */ const int64_t kh = hq / gqa; 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); /* The keys this row sees: [jlo, jhi) before the block table is consulted. */ 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); } const int64_t qoff = tok * q_rs + hq * q_hs, ooff = tok * o_rs + hq * o_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 + s; j < jhi; j += kSgs) { const int64_t blk = ld_index(btdt, btb, sq * bt_rs + (j / block_size) * bt_cs); if (blk < 0) continue; /* uniform across the sub-group */ const int64_t kb = blk * sb + kh * sh + (j % block_size) * so; float part = 0.0f; for (int e = 0; e < per; ++e) part += qv[e] * (rad_load_f32(cb, cdt, kb + (lane * per + e) * sd) * kds); const float sc = sycl::reduce_over_group(sg, part, 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 (lane == 0) { sm[s] = m; sl[s] = l; } for (int e = 0; e < per; ++e) sacc[((size_t)s * kSub + lane) * kMaxPer + e] = acc[e]; sycl::group_barrier(it.get_group()); if (s != 0) return; /* sub-group 0 merges and stores */ float M = -INFINITY; for (int t = 0; t < kSgs; ++t) M = sycl::fmax(M, sm[t]); if (M == -INFINITY) { for (int e = 0; e < per; ++e) rad_store_f32(ob, odt, ooff + (lane * per + e) * o_ds, 0.0f); return; } float L = 0.0f, out[kMaxPer]; for (int e = 0; e < kMaxPer; ++e) out[e] = 0.0f; for (int t = 0; t < kSgs; ++t) { if (sm[t] == -INFINITY) continue; const float f = sycl::exp(sm[t] - M); L += sl[t] * f; for (int e = 0; e < per; ++e) out[e] += sacc[((size_t)t * kSub + lane) * kMaxPer + 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