/* xe2_attn.cpp -- the paged KV cache: kv_store writes a step's keys and values, attn_paged reads * them. The layout is libref's (ref_attn.cpp) and libr4d's: * * kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim] K then V inside a slot * * read through the cache tensor's own strides when it is rank 4. * * attn_paged, correctness first: one work-group a (query row, head), computing libref's arithmetic * in libref's order, so the result is the reference's: * pass 1 lanes take keys; each key's dot q . (k * k_descale) is summed over d serially by its * lane, scaled, and the group takes the max; * pass 2 keys in chunks of kChunk: lanes compute w_j = exp(s_j - max) (in double, as libref's * ref_exp) into local memory, lane 0 adds them to the sum in key order, and lane d adds * w_j * (v_j[d] * v_descale) to acc[d] in key order. * Scores are recomputed in pass 2 rather than kept: 131072 keys of them do not fit local memory. * The mask, the zero row for no visible key, ragged batches (cu_seqlens) and sliding windows are * libref's. The fast kernels (split-KV decode, XMX prefill) are Phase 4's. * * kv_store skips a slot past the cache (libref refuses the whole launch after reading every slot * on the host, which a device launch cannot do without waiting) and a negative slot (libref's * padding rule). An fp8 cache stores k / k_scale and v / v_scale, as libref. */ #include "xe2_common.h" #include "xe2_ops.h" #include namespace xe2 { namespace { 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]; } struct KVView { int64_t sb, sh, so, sd; /* strides: block, kv head, slot offset, element */ }; KVView kv_view(const RadTensor* c, int64_t head_dim, int64_t block_size, int64_t kv_heads) { KVView v{}; if (c->rank == 4) { v.sb = c->stride[0]; v.sh = c->stride[1]; v.so = c->stride[2]; v.sd = c->stride[3]; } else { v.sd = 1; v.so = 2 * head_dim; v.sh = block_size * v.so; v.sb = kv_heads * v.sh; } return v; } constexpr int kMaxHd = 512; constexpr int kChunk = 256; } // namespace /* ------------------------------------------------------------------ kv_store */ int kv_store(const RadArgs* a, RadStream st) { if (!rad_args_have(a, 4)) return RAD_E_INVAL; const RadTensor *K = &a->t[0], *V = &a->t[1], *SM = &a->t[2], *KV = &a->t[3]; const int64_t head_dim = rad_args_geti_or(a, "head_dim", K->rank >= 3 ? K->shape[K->rank - 1] : 0); const int64_t block_size = rad_args_geti_or(a, "block_size", 0); const int64_t kv_heads = rad_args_geti_or(a, "n_head_kv", KV->rank == 4 ? KV->shape[1] : 0); if (head_dim <= 0 || block_size <= 0 || kv_heads <= 0) return RAD_E_SHAPE; if (KV->rank == 4 && (KV->shape[1] != kv_heads || KV->shape[2] != block_size || KV->shape[3] < 2 * head_dim)) return RAD_E_SHAPE; const int64_t M = rad_tensor_numel(SM); if (M <= 0 || rad_tensor_numel(K) < M * kv_heads * head_dim) return RAD_E_SHAPE; if (!rad_tensor_is_contiguous(SM)) return refuse("kv_store: slot_mapping not contiguous"); const int64_t n_blocks = KV->rank == 4 ? KV->shape[0] : 0; const int64_t k_ds = K->rank >= 2 ? K->stride[K->rank - 1] : 1; const int64_t k_hs = K->rank >= 3 ? K->stride[K->rank - 2] : head_dim * k_ds; const int64_t k_rs = row_stride(K, kv_heads * head_dim); const int64_t v_ds = V->rank >= 2 ? V->stride[V->rank - 1] : 1; const int64_t v_hs = V->rank >= 3 ? V->stride[V->rank - 2] : head_dim * v_ds; const int64_t v_rs = row_stride(V, kv_heads * head_dim); const KVView kvv = kv_view(KV, head_dim, block_size, kv_heads); const bool fp8 = KV->dtype == RAD_F8E4M3 || KV->dtype == RAD_F8E5M2; const float ks = fp8 ? 1.0f / (float)rad_args_getf_or(a, "k_scale", 1.0) : 1.0f; const float vs = fp8 ? 1.0f / (float)rad_args_getf_or(a, "v_scale", 1.0) : 1.0f; const char *kb = (const char*)K->data, *vb = (const char*)V->data, *sb = (const char*)SM->data; char* cb = (char*)KV->data; const uint32_t kdt = K->dtype, vdt = V->dtype, sdt = SM->dtype, cdt = KV->dtype; const int64_t per_tok = kv_heads * head_dim; const int64_t total = M * per_tok; sycl::queue* q = queue_of(st); if (!q) return RAD_E_DEVICE; const size_t wg = 128; const size_t groups = (size_t)((total + (int64_t)wg - 1) / (int64_t)wg); return submit([&] { syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) { const int64_t g = (int64_t)it.get_global_id(0); if (g >= total) return; const int64_t t = g / per_tok, h = (g / head_dim) % kv_heads, d = g % head_dim; const int64_t slot = ld_index(sdt, sb, t); if (slot < 0) return; const int64_t blk = slot / block_size, off = slot % block_size; if (n_blocks > 0 && blk >= n_blocks) return; const int64_t c = blk * kvv.sb + h * kvv.sh + off * kvv.so; rad_store_f32(cb, cdt, c + d * kvv.sd, rad_load_f32(kb, kdt, t * k_rs + h * k_hs + d * k_ds) * ks); rad_store_f32(cb, cdt, c + (head_dim + d) * kvv.sd, rad_load_f32(vb, vdt, t * v_rs + h * v_hs + d * v_ds) * vs); }); }); } /* ------------------------------------------------------------------ attn_paged */ int attn_paged(const RadArgs* a, RadStream 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); 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 (head_dim <= 0 || gqa <= 0 || block_size <= 0) return RAD_E_SHAPE; if (head_dim > kMaxHd) return refuse("attn_paged: head_dim %lld over %d", (long long)head_dim, kMaxHd); const int64_t kv_heads = KV->rank == 4 ? KV->shape[1] : 0; 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->rank == 4 && KV->shape[2] != block_size) return RAD_E_SHAPE; if (KV->rank == 4 && KV->shape[3] < 2 * head_dim) return RAD_E_SHAPE; if (!rad_tensor_is_contiguous(SU) || (CU && !rad_tensor_is_contiguous(CU))) return refuse("attn_paged: seqused / cu_seqlens not contiguous"); if ((KD && !rad_tensor_is_contiguous(KD)) || (VD && !rad_tensor_is_contiguous(VD))) return refuse("attn_paged: descales not contiguous"); 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 KVView kvv = kv_view(KV, head_dim, block_size, kv_heads); 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); /* libref's default, 1 / sqrt(head_dim) in f32. */ const float scale_f = (float)rad_args_getf_or(a, "scale", (double)(1.0f / std::sqrt((float)head_dim))); const int64_t jcap = max_blocks * block_size; 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; const size_t wg = (size_t)((head_dim + 15) / 16 * 16) < 64 ? 64 : (size_t)((head_dim + 15) / 16 * 16); sycl::queue* q = queue_of(st); if (!q) return RAD_E_DEVICE; return submit([&] { q->submit([&](sycl::handler& h) { sycl::local_accessor qf(sycl::range<1>(kMaxHd), h); sycl::local_accessor wv(sycl::range<1>(kChunk), h); sycl::local_accessor kbv(sycl::range<1>(kChunk), h); h.parallel_for(sycl::nd_range<1>{(size_t)total * wg, wg}, [=](sycl::nd_item<1> it) { const int64_t idx = (int64_t)it.get_group(0); const int lane = (int)it.get_local_id(0); const auto grp = it.get_group(); const int64_t hq = idx % q_heads, tok = idx / q_heads; int64_t s = 0, qlen = q_len_all, i = 0; if (cub) { while (s + 1 < n_seq && ld_index(cudt, cub, s + 1) <= tok) ++s; qlen = ld_index(cudt, cub, s + 1) - ld_index(cudt, cub, s); i = tok - ld_index(cudt, cub, s); } else { s = tok / q_len_all; i = tok - s * 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, s); const int64_t pos = ctx - qlen + i; const int64_t qoff = tok * q_rs + hq * q_hs; const int64_t ooff = tok * o_rs + hq * o_hs; const float kds = kdb ? rad_load_f32(kdb, kddt, s * kv_heads + kh) : 1.0f; const float vds = vdb ? rad_load_f32(vdb, vddt, s * kv_heads + kh) : 1.0f; const int64_t jend = sycl::min(ctx, jcap); auto key_at = [&](int64_t j) -> int64_t { if (causal && j > pos) return -1; if (window > 0) { const int64_t d = pos - j; if (causal ? (d >= window) : (d >= window || d <= -window)) return -1; } const int64_t blk = ld_index(btdt, btb, s * bt_rs + (j / block_size) * bt_cs); return blk < 0 ? -1 : blk * kvv.sb + kh * kvv.sh + (j % block_size) * kvv.so; }; auto score = [&](int64_t kb) { float dot = 0.0f; for (int64_t d = 0; d < head_dim; ++d) dot += qf[d] * (rad_load_f32(cb, cdt, kb + d * kvv.sd) * kds); return dot * scale_f; }; for (int64_t d = lane; d < head_dim; d += (int64_t)wg) qf[d] = rad_load_f32(qb, qdt, qoff + d * q_ds); sycl::group_barrier(grp); /* Pass 1: the max score. */ float mx = -INFINITY; for (int64_t j = lane; j < jend; j += (int64_t)wg) { const int64_t kb = key_at(j); if (kb >= 0) mx = sycl::fmax(mx, score(kb)); } mx = sycl::reduce_over_group(grp, mx, sycl::maximum()); if (mx == -INFINITY) { for (int64_t d = lane; d < head_dim; d += (int64_t)wg) rad_store_f32(ob, odt, ooff + d * o_ds, 0.0f); return; } /* Pass 2: weights by chunk, the sum and acc[d] in key order. */ float acc = 0.0f; /* acc[lane], lanes past head_dim idle */ float sum = 0.0f; /* lane 0's */ for (int64_t c0 = 0; c0 < jend; c0 += kChunk) { const int64_t cn = sycl::min((int64_t)kChunk, jend - c0); for (int64_t jj = lane; jj < cn; jj += (int64_t)wg) { const int64_t kb = key_at(c0 + jj); kbv[jj] = kb; wv[jj] = kb >= 0 ? (float)sycl::exp((double)(score(kb) - mx)) : 0.0f; } sycl::group_barrier(grp); if (lane == 0) for (int64_t jj = 0; jj < cn; ++jj) if (kbv[jj] >= 0) sum += wv[jj]; if (lane < head_dim) for (int64_t jj = 0; jj < cn; ++jj) { const int64_t kb = kbv[jj]; if (kb < 0) continue; acc += wv[jj] * (rad_load_f32(cb, cdt, kb + (head_dim + lane) * kvv.sd) * vds); } sycl::group_barrier(grp); } sum = sycl::group_broadcast(grp, sum, 0); const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; if (lane < head_dim) rad_store_f32(ob, odt, ooff + lane * o_ds, acc * inv); }); }); }); } } // namespace xe2