diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index a0e46936..013094b6 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -189,9 +189,9 @@ typedef struct RadBatch { /* The longest query in each half. max_q_len over a mixed step is the prefill chunk's, and * banding the decode half with it would give eight rows a thousand-row GEMM's band. * - * Only the decode value is currently read (by the GDN blocks). The prefill value is for a - * block whose prefill path bands on a per-sequence query length; the GDN prefill ops band on - * the step's total tokens, taken from their operands. */ + * The decode value is read by the GDN blocks and the fp8 gated attention's per-band issue + * (rad_block_attn_gated_fp8.h), which also bands its prefill half on the prefill value; the + * GDN prefill ops band on the step's total tokens, taken from their operands. */ int32_t max_q_len_decode; int32_t max_q_len_prefill; diff --git a/arch/common/rad_block_attn_gated_fp8.h b/arch/common/rad_block_attn_gated_fp8.h index 47a01531..bbc70474 100644 --- a/arch/common/rad_block_attn_gated_fp8.h +++ b/arch/common/rad_block_attn_gated_fp8.h @@ -21,11 +21,23 @@ #include "rad_fp8.h" +#include #include namespace rad { namespace arch { +/* RADIANCE_ATTN_BAND_SPLIT=0 issues a mixed step's dense attention as one launch at the step's + * widest band, as before the per-band issue in AttnGatedFP8::step; unset or anything else splits. + * An A/B and debugging knob, not configuration. Read once. */ +inline bool attn_band_split() { + static const bool on = [] { + const char* e = std::getenv("RADIANCE_ATTN_BAND_SPLIT"); + return !(e && !std::strcmp(e, "0")); + }(); + return on; +} + struct AttnGatedFP8 { struct Wire { rad_buf x = 0; /* [max_tok, n_embd] the residual stream */ @@ -653,15 +665,57 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar, brow_slice(w.attn.x, off, rows, qw)); } } else { - RAD_ISSUE_N(c, op_attn, batch->max_q_len, - brows(w.q, T), kv_cache(kv, layer), - praw2(table, RAD_I32, batch->n_seq, - kvb ? kvb->block_table_pitch : 0), - praw(used, RAD_I32, batch->n_seq), - RAD_NONE, RAD_NONE, - /* cu_seqlens: the batch may be ragged (a prefill chunk beside decode rows). */ - praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), - brows(w.attn.x, T)); + /* A mixed step once per band, as the GDN blocks issue theirs (rad_block_gdn_fp8.h): one + * launch at the chunk's band would serve the decode rows by the query-tiled prefill kernel, + * one workgroup a kv head walking each decode sequence's whole context, the step's tail + * beside a chunk of thousands of rows (one sequence decoding at 188k beside a 25k prompt's + * 2048-row chunks: 512 ms a mixed step against 218 ms at 0.7k of context, the prompt's + * prefill 5.1 -> 11.3 s). The decode half, sequences [0, D) and rows [0, DT), is the prefix: + * its own band (the split-KV decode row) over its rows, tables and cu. The prefill half + * takes its per-sequence arrays past the decode sequences and keeps q, out and cu at their + * absolute rows (the kernels index q and out by cu, and the merge of a split launch keeps + * to cu's span). + * + * The prefill half is issued at the op's top band (max_tok), not at its own query length: + * a launch over part of the step (q and out whole, cu past row 0, as ArPieces issues its + * pieces) is served by the query-tiled row, while the band of a short chunk (10 rows or + * fewer at gqa 6) is the split-KV decode row's, whose partials are laid out by the step's + * rows and sized at declare for its own band: 1.10-next6u issued it there and stopped + * under load on RAD_E_SCRATCH. Kernels read exact lengths from cu, so the loose band costs + * nothing. A chunk no longer than the verify blocks beside it keeps the one launch at + * their band, as before the split: the whole step is decode-shaped then. + * + * Pure steps issue one launch, as before. */ + int64_t D = 0, DT = 0; + batch_split(batch, &D, &DT); + const int64_t pitch = kvb ? kvb->block_table_pitch : 0; + const int32_t qp = batch->max_q_len_prefill > 0 ? batch->max_q_len_prefill + : batch->max_q_len; + if (batch->phase == RAD_PHASE_MIXED && D > 0 && D < batch->n_seq && + batch->max_q_len_decode > 0 && qp > batch->max_q_len_decode && attn_band_split()) { + const int64_t P = batch->n_seq - D; + RAD_ISSUE_N(c, op_attn, batch->max_q_len_decode, + brows(w.q, DT), kv_cache(kv, layer), + praw2(table, RAD_I32, D, pitch), praw(used, RAD_I32, D), + RAD_NONE, RAD_NONE, praw(batch->cu_seqlens, RAD_I32, D + 1), + brows(w.attn.x, DT)); + RAD_ISSUE_N(c, op_attn, g.max_tok, + brows(w.q, T), kv_cache(kv, layer), + praw2(table ? table + D * pitch : nullptr, RAD_I32, P, pitch), + praw(used ? used + D : nullptr, RAD_I32, P), + RAD_NONE, RAD_NONE, praw(batch->cu_seqlens + D, RAD_I32, P + 1), + brows(w.attn.x, T)); + } else { + RAD_ISSUE_N(c, op_attn, batch->max_q_len, + brows(w.q, T), kv_cache(kv, layer), + praw2(table, RAD_I32, batch->n_seq, pitch), + praw(used, RAD_I32, batch->n_seq), + RAD_NONE, RAD_NONE, + /* cu_seqlens: the batch may be ragged (verify rows of different + * lengths; a chunk beside decode rows at RADIANCE_ATTN_BAND_SPLIT=0). */ + praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), + brows(w.attn.x, T)); + } } if (gated) { diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index a568c26a..32c54d1e 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -1489,6 +1489,164 @@ static void attn_split_case(const Plugin& pl, const char* name, const char* kv_d dfree_all(); } +/* A mixed step's attention as the engine issues it (AttnGatedFP8::step's per-band issue) at + * Qwen3.8-27B's per-rank production geometry: `nd` decode sequences of 8-10 query rows (verify + * blocks) beside one prefill chunk of `pq` rows, max_seqs 16, max_ctx 200000, the band bounds 10 + * (decode) and 2048. Each band's row gets the scratch its hook sized at declare, from the band's + * frozen geometry and no tensors, and nothing more, as the core binds it (rad_builder.cpp, + * ctx.cpp): the decode half (prefix rows, its own cu) at the decode band; the prefill half (q and + * out whole, cu and the per-sequence arrays past the decode sequences) at band `pband`, which + * picks the row as the core would (at most 10: the decode row). Both launches must succeed, and + * every sequence's rows match the oracle afterwards: the prefill half must not write the decode + * rows. 1.10-next6u issued the prefill half at its own query length, so a chunk of 10 rows or + * fewer reached the decode row with the whole step's rows and refused for scratch. */ +static void attn_mixed_step_case(const Plugin& pl, const char* dec_name, const char* pre_name, + const char* kv_dtype, int nd, int64_t pq, int64_t pband) { + if (!sel(pre_name) && !sel("attn_mixed_step")) return; + const RadKernelInfo* rd = find(pl, dec_name); + const RadKernelInfo* rp = find(pl, pre_name); + const std::string tag = fmt("%s mixed step: %d decode rows of 8-10 + a %lld-row chunk, " + "prefill half at band %lld", pre_name, nd, (long long)pq, + (long long)pband); + if (!rd || !rp || !rd->scratch) { ok(tag.c_str(), false, "row or scratch hook absent"); return; } + const int64_t head_dim = 256, gqa = 6, kv_heads = 2, bs = 16, q_heads = kv_heads * gqa; + const int64_t dband = 10, max_seqs = 16, max_ctx = 200000, top = 2048; + const int kvq = !std::strcmp(kv_dtype, "fp8_v4") ? 1 : !std::strcmp(kv_dtype, "k6_v4") ? 2 : 0; + const int64_t rowe = kvq == 2 ? 22 * head_dim / 16 : kvq == 1 ? 25 * head_dim / 16 : head_dim * 2; + const int64_t voff = kvq == 2 ? head_dim * 3 / 4 : head_dim; + const int64_t vsoff = kvq == 2 ? head_dim * 21 / 16 : head_dim * 3 / 2; + const float scale = 1.0f / std::sqrt((float)head_dim); + + /* decode-first, as the scheduler sorts a step; contexts differ per sequence */ + const int64_t ns = nd + 1; + std::vector ql, cx; + for (int s = 0; s < nd; ++s) { ql.push_back(8 + s % 3); cx.push_back(3000 + 397 * s); } + ql.push_back(pq); cx.push_back(pq + 2500); + int64_t mb = 0; + std::vector cu(1, 0), used; + for (int64_t s = 0; s < ns; ++s) { + cu.push_back(cu.back() + (int32_t)ql[(size_t)s]); + used.push_back((int32_t)cx[(size_t)s]); + mb = std::max(mb, (cx[(size_t)s] + bs - 1) / bs); + } + const int64_t nt = cu.back(), DT = cu[(size_t)nd]; + const std::vector bt = iota_i32(ns * mb); + + std::vector qh((size_t)(nt * q_heads * head_dim)); + for (size_t i = 0; i < qh.size(); ++i) qh[i] = st_rand_bf16(i); + const int64_t nelem = ns * mb * kv_heads * bs * rowe; + std::vector kv((size_t)nelem); + for (int64_t e = 0; e < nelem; ++e) kv[(size_t)e] = st_rand_e4m3(e); + if (kvq) + for (int64_t r0 = 0; r0 < nelem; r0 += rowe) { + uint8_t* row = &kv[(size_t)r0]; + for (int64_t b = 0; b < head_dim / 2; ++b) + row[voff + b] = (uint8_t)(st_rand_e4m3(r0 * 7 + b) * 37u + (uint32_t)b); + for (int64_t g = 0; g < head_dim / 32; ++g) { + const _Float16 s = (_Float16)(0.015625f * (float)(1 + (st_rand_e4m3(r0 + g) & 15))); + std::memcpy(row + vsoff + g * 2, &s, 2); + } + if (kvq == 2) { + for (int64_t b = 0; b < head_dim * 3 / 4; ++b) + row[b] = (uint8_t)(st_rand_e4m3(r0 * 5 + b + 11) * 29u + (uint32_t)(3 * b)); + for (int64_t g = 0; g < head_dim / 32; ++g) { + const _Float16 s = (_Float16)(0.00390625f * (float)(1 + (st_rand_e4m3(r0 + g + 7) & 15))); + std::memcpy(row + head_dim * 5 / 4 + g * 2, &s, 2); + } + } + } + const size_t on = (size_t)(nt * q_heads * head_dim); + void* d_q = dalloc(on * 2); + void* d_kv = dalloc(kv.size()); + void* d_o = dalloc(on * 2); + if (!d_q || !d_kv || !d_o) { ok(tag.c_str(), false, "hipMalloc failed"); dfree_all(); return; } + st_memcpy(d_q, qh.data(), on * 2, hipMemcpyHostToDevice); + st_memcpy(d_kv, kv.data(), kv.size(), hipMemcpyHostToDevice); + st_memset(d_o, 0xff, on * 2); + + /* A band's frozen geometry: the op's parameters with q_len at the band's bound. */ + auto geom = [&](int64_t band) { + return std::vector{ + PI("q_len", band), PI("head_dim", head_dim), PI("gqa", gqa), PI("causal", 1), + PI("window", 0), PI("n_head", q_heads), PI("block_size", bs), + PI("max_seqs", max_seqs), PI("max_ctx", max_ctx), PS("q_dtype", "bf16"), + PS("kv_dtype", kv_dtype) }; + }; + /* the core's sizing: the hook at the band's geometry, no tensors */ + auto declared = [&](const RadKernelInfo* r, int64_t band) -> int64_t { + if (!r->scratch) return 0; + std::vector ps = geom(band); + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; + return r->scratch(&a); + }; + /* one issue: rows [r0 .. r0 + rows) of q/out are the tensors' extent from row 0 (prefix) or + * the whole step; sequences [s0, s0 + n) */ + std::string why; + auto issue = [&](int64_t band, int64_t rows, int64_t s0, int64_t n) { + const RadKernelInfo* r = band <= dband ? rd : rp; + const int64_t sb = declared(r, band <= dband ? dband : top); + void* scr = sb > 0 ? dalloc((size_t)sb) : nullptr; + if (scr) st_memset(scr, 0x7f, (size_t)sb); + const std::vector bth(bt.begin() + s0 * mb, bt.begin() + (s0 + n) * mb); + const std::vector uh(used.begin() + s0, used.begin() + s0 + n); + const std::vector ch(cu.begin() + s0, cu.begin() + s0 + n + 1); + std::vector ts = { + T(d_q, RAD_BF16, { rows, q_heads, head_dim }), + T(d_kv, RAD_F8E4M3, { ns * mb, kv_heads, bs, rowe }), + TI32({ n, mb }, bth), TI32({ n }, uh), + TF32({ n, kv_heads }, 1.0f), TF32({ n, kv_heads }, 1.0f), + TI32({ n + 1 }, ch), + T(d_o, RAD_BF16, { rows, q_heads, head_dim }), + }; + std::vector ps = geom(band <= dband ? dband : top); + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; + a.scratch = scr; a.scratch_bytes = sb; + const int rc = r->launch(&a, nullptr); + const hipError_t he = (hipError_t)st_stream_sync(nullptr); + if (rc != RAD_OK || he != hipSuccess) + why += fmt("%s%s at band %lld (%lld rows, %lld sequences, scratch %lld) rc=%d hip=%d", + why.empty() ? "" : "; ", r->name, (long long)band, (long long)rows, + (long long)n, (long long)sb, rc, (int)he); + }; + int dq = 0; + for (int s = 0; s < nd; ++s) dq = std::max(dq, (int)ql[(size_t)s]); + issue(dq, DT, 0, nd); /* the decode half, at its band (<= 10) */ + issue(pband, nt, nd, 1); /* the prefill half */ + + std::vector oh(on); + st_memcpy(oh.data(), d_o, on * 2, hipMemcpyDeviceToHost); + const float abs_tol = 1e-3f, rel_tol = 2e-2f; + float max_err = 0.0f; + int bad = 0, nchk = 0; + for (int64_t s = 0; s < ns; ++s) { + const int64_t q = ql[(size_t)s]; + for (const int64_t i : { (int64_t)0, q / 2, q - 1 }) { + const int64_t tok = cu[(size_t)s] + i; + for (int64_t h = 0; h < q_heads; ++h) { + float ref[256]; + attn_oracle_one(&qh[(size_t)((tok * q_heads + h) * head_dim)], kv.data(), 1, + head_dim, kv_heads, bs, h / gqa, &bt[(size_t)(s * mb)], mb, + (int)cx[(size_t)s], 1.0f, 1.0f, 1, 0, scale, q, i, ref, kvq); + for (int64_t d = 0; d < head_dim; ++d) { + const float got = h_bf16(oh[(size_t)((tok * q_heads + h) * head_dim + d)]); + const float diff = std::fabs(got - ref[d]); + if (!(diff <= abs_tol + rel_tol * std::fabs(ref[d]))) ++bad; + if (diff > max_err) max_err = diff; + ++nchk; + } + } + } + } + ok(tag.c_str(), why.empty() && bad == 0, + why.empty() ? fmt("max_err=%.5g bad=%d/%d", max_err, bad, nchk) : why); + dfree_all(); +} + /* The split's scratch at declare (the band's bound 2048, Qwen3.8-27B's per-rank 12 heads over 2, * the model's context, no tensors): the hook must cover the largest launch the law can split in the * band, over every sequence count up to max_seqs, and stay near the 25.4 MB bound its comment @@ -26399,6 +26557,16 @@ static void device_phase(const Plugin& pl) { attn_split_case(pl, n, kv, { { 64, 9000 }, { 11, 8192 } }, 6, true, 3, 0); attn_split_scratch_case(pl, n, kv); } + /* A mixed step's two halves at the production geometry, each with only its band's declared + * scratch: up to 15 verify blocks beside chunks of 1 to 640 rows. */ + for (const auto& sr : { std::make_pair("attn_prefill_h256_gqa6_k6v4", "k6_v4"), + std::make_pair("attn_prefill_h256_gqa6_fp8v4", "fp8_v4") }) { + const std::string dec = std::string("attn_decode_h256_gqa6_") + (sr.second[0] == 'k' ? "k6v4" : "fp8v4"); + for (const auto& c : { std::make_pair(15, 5), std::make_pair(15, 10), std::make_pair(3, 1), + std::make_pair(8, 53), std::make_pair(1, 300), + std::make_pair(15, 640) }) + attn_mixed_step_case(pl, dec.c_str(), sr.first, sr.second, c.first, c.second, 2048); + } /* Flash-Next's QSA layers: twelve queries per KV head over 4-token pages, and six at * four ranks, each layout's prefill (a long history and a ragged last tile), decode, and the * widest verify (q_len 5 at gqa 12, 10 at gqa 6). */ diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 3b81ddea..85a408ed 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -7015,6 +7015,88 @@ TEST(qwen35_fp8_steps_lint_clean_with_its_mtp_head) { lint_qwen35_fp8_family(qwen35_fp8::declare, qwen35_fp8::step, mk.meta(), 3, false, 0); } +/* The dense attention of a mixed step is issued once per band (AttnGatedFP8::step): the decode + * sequences at their own band (the split-KV decode row), then the prefill chunks at theirs, so a + * long decode sequence riding a prefill chunk is not walked by one query-tiled workgroup. The + * decode half is the prefix (its rows, its tables, cu to its end); the prefill half has its + * per-sequence arrays past the decode sequences and q, out and cu at their absolute rows, as the + * GDN blocks issue their prefill half, at the op's top band so a row written for such a launch + * serves it. A pure step issues one attention per layer, as before + * (and with RADIANCE_ATTN_BAND_SPLIT=0, under which every pinned_steps pin of the families on this + * block holds unchanged, so a mixed step is the only one the split touches). */ +TEST(qwen35_fp8_issues_a_mixed_steps_attention_once_per_band) { + MetaKV mk = q35fp8_meta(); + RadBuilder b; + RadBuildCtx ctx = build_ctx(); + REQUIRE_EQ(qwen35_fp8::declare(&b, mk.meta(), &ctx), RAD_OK); + /* A verify of 4 and a plain decode beside a 6-row chunk over 20 tokens of history. */ + const auto mixed = kit(b, { 4, 1 }, { 6 }, 20); + const auto dec = kit(b, { 4, 1 }, {}); + const auto pre = kit(b, {}, { 6 }, 20); + auto attn = [&](const Kit& k) { + const auto v = run_passes(b, qwen35_fp8::step, { &k }); + CHECK(steps_ok(v)); + CHECK_LINT(b, v[0].get()); + std::vector out; + for (const auto& i : v[0]->issues) { + const RecOp* o = b.op_of(i.op); + if (o && o->op == "attn_paged") out.push_back(i); + } + return out; + }; + /* two attention layers in the fixture */ + CHECK_EQ(attn(*dec).size(), (size_t)2); + CHECK_EQ(attn(*pre).size(), (size_t)2); + const auto m = attn(*mixed); + if (!rad::arch::attn_band_split()) { /* RADIANCE_ATTN_BAND_SPLIT=0: one launch */ + CHECK_EQ(m.size(), (size_t)2); + return; + } + REQUIRE_EQ(m.size(), (size_t)4); + const int32_t* table = mixed->table.data(); + const int32_t* used = mixed->used.data(); + const int32_t* cu = mixed->cu.data(); + for (size_t l = 0; l < 2; ++l) { + const RecIssue& d = m[2 * l]; + const RecIssue& p = m[2 * l + 1]; + REQUIRE(d.opd.size() == 8 && p.opd.size() == 8); + CHECK_EQ(d.n, (int64_t)4); /* the decode band: the verify's 4 */ + CHECK_EQ(d.opd[0].rows, (int64_t)5); /* q: the 5 decode rows */ + CHECK(d.opd[2].raw == (void*)table); CHECK_EQ(d.opd[2].rows, (int64_t)2); + CHECK(d.opd[3].raw == (void*)used); CHECK_EQ(d.opd[3].rows, (int64_t)2); + CHECK(d.opd[6].raw == (void*)cu); CHECK_EQ(d.opd[6].rows, (int64_t)3); + CHECK_EQ(d.opd[7].rows, (int64_t)5); + CHECK_EQ(p.n, (int64_t)256); /* the top band, whatever the chunk */ + CHECK_EQ(p.opd[0].rows, (int64_t)11); /* q and out whole: cu is absolute */ + CHECK(p.opd[2].raw == (void*)(table + 2 * 16)); CHECK_EQ(p.opd[2].rows, (int64_t)1); + CHECK(p.opd[3].raw == (void*)(used + 2)); CHECK_EQ(p.opd[3].rows, (int64_t)1); + CHECK(p.opd[6].raw == (void*)(cu + 2)); CHECK_EQ(p.opd[6].rows, (int64_t)2); + CHECK_EQ(p.opd[7].rows, (int64_t)11); + CHECK_EQ(d.opd[1].handle, p.opd[1].handle); /* the same layer's cache */ + CHECK_EQ(d.opd[1].offset, p.opd[1].offset); + } + /* A chunk no longer than the decode band's bound (1.10-next6u issued it at its own 10 and + * the decode row took the whole step's rows: RAD_E_SCRATCH under load) still goes to the top + * band; a chunk no longer than the verify blocks beside it keeps the one launch at their + * band, as before the split (r4d_selftest attn_mixed_step checks both halves' scratch). */ + const auto shortc = kit(b, { 3, 2 }, { 4 }, 20); + const auto m2 = attn(*shortc); + REQUIRE_EQ(m2.size(), (size_t)4); + for (size_t l = 0; l < 2; ++l) { + CHECK_EQ(m2[2 * l].n, (int64_t)3); + CHECK_EQ(m2[2 * l + 1].n, (int64_t)256); + CHECK_EQ(m2[2 * l + 1].opd[0].rows, (int64_t)9); + } + const auto tiny = kit(b, { 4, 3 }, { 2 }, 20); + const auto m3 = attn(*tiny); + REQUIRE_EQ(m3.size(), (size_t)2); + for (const RecIssue& i : m3) { + CHECK_EQ(i.n, (int64_t)4); + CHECK_EQ(i.opd[0].rows, (int64_t)9); + CHECK_EQ(i.opd[6].rows, (int64_t)4); + } +} + namespace { /* Every trunk and MTP linear of a qwen35 container in the 4-bit form an int4 W4A16 release